1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/rt/emul/compact/src/main/java/java/lang/invoke/MethodHandles.java Sat Aug 09 11:11:13 2014 +0200
1.3 @@ -0,0 +1,2848 @@
1.4 +/*
1.5 + * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1.7 + *
1.8 + * This code is free software; you can redistribute it and/or modify it
1.9 + * under the terms of the GNU General Public License version 2 only, as
1.10 + * published by the Free Software Foundation. Oracle designates this
1.11 + * particular file as subject to the "Classpath" exception as provided
1.12 + * by Oracle in the LICENSE file that accompanied this code.
1.13 + *
1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1.17 + * version 2 for more details (a copy is included in the LICENSE file that
1.18 + * accompanied this code).
1.19 + *
1.20 + * You should have received a copy of the GNU General Public License version
1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1.23 + *
1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1.25 + * or visit www.oracle.com if you need additional information or have any
1.26 + * questions.
1.27 + */
1.28 +
1.29 +package java.lang.invoke;
1.30 +
1.31 +import java.lang.reflect.*;
1.32 +import java.util.List;
1.33 +import java.util.ArrayList;
1.34 +import java.util.Arrays;
1.35 +
1.36 +import sun.invoke.util.ValueConversions;
1.37 +import sun.invoke.util.VerifyAccess;
1.38 +import sun.invoke.util.Wrapper;
1.39 +import sun.reflect.CallerSensitive;
1.40 +import sun.reflect.Reflection;
1.41 +import sun.reflect.misc.ReflectUtil;
1.42 +import sun.security.util.SecurityConstants;
1.43 +import static java.lang.invoke.MethodHandleStatics.*;
1.44 +import static java.lang.invoke.MethodHandleNatives.Constants.*;
1.45 +import java.util.concurrent.ConcurrentHashMap;
1.46 +import sun.security.util.SecurityConstants;
1.47 +
1.48 +/**
1.49 + * This class consists exclusively of static methods that operate on or return
1.50 + * method handles. They fall into several categories:
1.51 + * <ul>
1.52 + * <li>Lookup methods which help create method handles for methods and fields.
1.53 + * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
1.54 + * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
1.55 + * </ul>
1.56 + * <p>
1.57 + * @author John Rose, JSR 292 EG
1.58 + * @since 1.7
1.59 + */
1.60 +public class MethodHandles {
1.61 +
1.62 + private MethodHandles() { } // do not instantiate
1.63 +
1.64 + private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
1.65 + static { MethodHandleImpl.initStatics(); }
1.66 + // See IMPL_LOOKUP below.
1.67 +
1.68 + //// Method handle creation from ordinary methods.
1.69 +
1.70 + /**
1.71 + * Returns a {@link Lookup lookup object} with
1.72 + * full capabilities to emulate all supported bytecode behaviors of the caller.
1.73 + * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
1.74 + * Factory methods on the lookup object can create
1.75 + * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
1.76 + * for any member that the caller has access to via bytecodes,
1.77 + * including protected and private fields and methods.
1.78 + * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
1.79 + * Do not store it in place where untrusted code can access it.
1.80 + * <p>
1.81 + * This method is caller sensitive, which means that it may return different
1.82 + * values to different callers.
1.83 + * <p>
1.84 + * For any given caller class {@code C}, the lookup object returned by this call
1.85 + * has equivalent capabilities to any lookup object
1.86 + * supplied by the JVM to the bootstrap method of an
1.87 + * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
1.88 + * executing in the same caller class {@code C}.
1.89 + * @return a lookup object for the caller of this method, with private access
1.90 + */
1.91 + @CallerSensitive
1.92 + public static Lookup lookup() {
1.93 + return new Lookup(Reflection.getCallerClass());
1.94 + }
1.95 +
1.96 + /**
1.97 + * Returns a {@link Lookup lookup object} which is trusted minimally.
1.98 + * It can only be used to create method handles to
1.99 + * publicly accessible fields and methods.
1.100 + * <p>
1.101 + * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
1.102 + * of this lookup object will be {@link java.lang.Object}.
1.103 + *
1.104 + * <p style="font-size:smaller;">
1.105 + * <em>Discussion:</em>
1.106 + * The lookup class can be changed to any other class {@code C} using an expression of the form
1.107 + * {@link Lookup#in publicLookup().in(C.class)}.
1.108 + * Since all classes have equal access to public names,
1.109 + * such a change would confer no new access rights.
1.110 + * A public lookup object is always subject to
1.111 + * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
1.112 + * Also, it cannot access
1.113 + * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
1.114 + * @return a lookup object which is trusted minimally
1.115 + */
1.116 + public static Lookup publicLookup() {
1.117 + return Lookup.PUBLIC_LOOKUP;
1.118 + }
1.119 +
1.120 + /**
1.121 + * Performs an unchecked "crack" of a
1.122 + * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
1.123 + * The result is as if the user had obtained a lookup object capable enough
1.124 + * to crack the target method handle, called
1.125 + * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
1.126 + * on the target to obtain its symbolic reference, and then called
1.127 + * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
1.128 + * to resolve the symbolic reference to a member.
1.129 + * <p>
1.130 + * If there is a security manager, its {@code checkPermission} method
1.131 + * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
1.132 + * @param <T> the desired type of the result, either {@link Member} or a subtype
1.133 + * @param target a direct method handle to crack into symbolic reference components
1.134 + * @param expected a class object representing the desired result type {@code T}
1.135 + * @return a reference to the method, constructor, or field object
1.136 + * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
1.137 + * @exception NullPointerException if either argument is {@code null}
1.138 + * @exception IllegalArgumentException if the target is not a direct method handle
1.139 + * @exception ClassCastException if the member is not of the expected type
1.140 + * @since 1.8
1.141 + */
1.142 + public static <T extends Member> T
1.143 + reflectAs(Class<T> expected, MethodHandle target) {
1.144 + SecurityManager smgr = System.getSecurityManager();
1.145 + if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION);
1.146 + Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup
1.147 + return lookup.revealDirect(target).reflectAs(expected, lookup);
1.148 + }
1.149 + // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
1.150 + static final private java.security.Permission ACCESS_PERMISSION =
1.151 + new ReflectPermission("suppressAccessChecks");
1.152 +
1.153 + /**
1.154 + * A <em>lookup object</em> is a factory for creating method handles,
1.155 + * when the creation requires access checking.
1.156 + * Method handles do not perform
1.157 + * access checks when they are called, but rather when they are created.
1.158 + * Therefore, method handle access
1.159 + * restrictions must be enforced when a method handle is created.
1.160 + * The caller class against which those restrictions are enforced
1.161 + * is known as the {@linkplain #lookupClass lookup class}.
1.162 + * <p>
1.163 + * A lookup class which needs to create method handles will call
1.164 + * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
1.165 + * When the {@code Lookup} factory object is created, the identity of the lookup class is
1.166 + * determined, and securely stored in the {@code Lookup} object.
1.167 + * The lookup class (or its delegates) may then use factory methods
1.168 + * on the {@code Lookup} object to create method handles for access-checked members.
1.169 + * This includes all methods, constructors, and fields which are allowed to the lookup class,
1.170 + * even private ones.
1.171 + *
1.172 + * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
1.173 + * The factory methods on a {@code Lookup} object correspond to all major
1.174 + * use cases for methods, constructors, and fields.
1.175 + * Each method handle created by a factory method is the functional
1.176 + * equivalent of a particular <em>bytecode behavior</em>.
1.177 + * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
1.178 + * Here is a summary of the correspondence between these factory methods and
1.179 + * the behavior the resulting method handles:
1.180 + * <table border=1 cellpadding=5 summary="lookup method behaviors">
1.181 + * <tr>
1.182 + * <th><a name="equiv"></a>lookup expression</th>
1.183 + * <th>member</th>
1.184 + * <th>bytecode behavior</th>
1.185 + * </tr>
1.186 + * <tr>
1.187 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
1.188 + * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
1.189 + * </tr>
1.190 + * <tr>
1.191 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
1.192 + * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
1.193 + * </tr>
1.194 + * <tr>
1.195 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
1.196 + * <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
1.197 + * </tr>
1.198 + * <tr>
1.199 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
1.200 + * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
1.201 + * </tr>
1.202 + * <tr>
1.203 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
1.204 + * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
1.205 + * </tr>
1.206 + * <tr>
1.207 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
1.208 + * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
1.209 + * </tr>
1.210 + * <tr>
1.211 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
1.212 + * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
1.213 + * </tr>
1.214 + * <tr>
1.215 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
1.216 + * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
1.217 + * </tr>
1.218 + * <tr>
1.219 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
1.220 + * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
1.221 + * </tr>
1.222 + * <tr>
1.223 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
1.224 + * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
1.225 + * </tr>
1.226 + * <tr>
1.227 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
1.228 + * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
1.229 + * </tr>
1.230 + * <tr>
1.231 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
1.232 + * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
1.233 + * </tr>
1.234 + * <tr>
1.235 + * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
1.236 + * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
1.237 + * </tr>
1.238 + * </table>
1.239 + *
1.240 + * Here, the type {@code C} is the class or interface being searched for a member,
1.241 + * documented as a parameter named {@code refc} in the lookup methods.
1.242 + * The method type {@code MT} is composed from the return type {@code T}
1.243 + * and the sequence of argument types {@code A*}.
1.244 + * The constructor also has a sequence of argument types {@code A*} and
1.245 + * is deemed to return the newly-created object of type {@code C}.
1.246 + * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
1.247 + * The formal parameter {@code this} stands for the self-reference of type {@code C};
1.248 + * if it is present, it is always the leading argument to the method handle invocation.
1.249 + * (In the case of some {@code protected} members, {@code this} may be
1.250 + * restricted in type to the lookup class; see below.)
1.251 + * The name {@code arg} stands for all the other method handle arguments.
1.252 + * In the code examples for the Core Reflection API, the name {@code thisOrNull}
1.253 + * stands for a null reference if the accessed method or field is static,
1.254 + * and {@code this} otherwise.
1.255 + * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
1.256 + * for reflective objects corresponding to the given members.
1.257 + * <p>
1.258 + * In cases where the given member is of variable arity (i.e., a method or constructor)
1.259 + * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
1.260 + * In all other cases, the returned method handle will be of fixed arity.
1.261 + * <p style="font-size:smaller;">
1.262 + * <em>Discussion:</em>
1.263 + * The equivalence between looked-up method handles and underlying
1.264 + * class members and bytecode behaviors
1.265 + * can break down in a few ways:
1.266 + * <ul style="font-size:smaller;">
1.267 + * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
1.268 + * the lookup can still succeed, even when there is no equivalent
1.269 + * Java expression or bytecoded constant.
1.270 + * <li>Likewise, if {@code T} or {@code MT}
1.271 + * is not symbolically accessible from the lookup class's loader,
1.272 + * the lookup can still succeed.
1.273 + * For example, lookups for {@code MethodHandle.invokeExact} and
1.274 + * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
1.275 + * <li>If there is a security manager installed, it can forbid the lookup
1.276 + * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
1.277 + * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
1.278 + * constant is not subject to security manager checks.
1.279 + * <li>If the looked-up method has a
1.280 + * <a href="MethodHandle.html#maxarity">very large arity</a>,
1.281 + * the method handle creation may fail, due to the method handle
1.282 + * type having too many parameters.
1.283 + * </ul>
1.284 + *
1.285 + * <h1><a name="access"></a>Access checking</h1>
1.286 + * Access checks are applied in the factory methods of {@code Lookup},
1.287 + * when a method handle is created.
1.288 + * This is a key difference from the Core Reflection API, since
1.289 + * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
1.290 + * performs access checking against every caller, on every call.
1.291 + * <p>
1.292 + * All access checks start from a {@code Lookup} object, which
1.293 + * compares its recorded lookup class against all requests to
1.294 + * create method handles.
1.295 + * A single {@code Lookup} object can be used to create any number
1.296 + * of access-checked method handles, all checked against a single
1.297 + * lookup class.
1.298 + * <p>
1.299 + * A {@code Lookup} object can be shared with other trusted code,
1.300 + * such as a metaobject protocol.
1.301 + * A shared {@code Lookup} object delegates the capability
1.302 + * to create method handles on private members of the lookup class.
1.303 + * Even if privileged code uses the {@code Lookup} object,
1.304 + * the access checking is confined to the privileges of the
1.305 + * original lookup class.
1.306 + * <p>
1.307 + * A lookup can fail, because
1.308 + * the containing class is not accessible to the lookup class, or
1.309 + * because the desired class member is missing, or because the
1.310 + * desired class member is not accessible to the lookup class, or
1.311 + * because the lookup object is not trusted enough to access the member.
1.312 + * In any of these cases, a {@code ReflectiveOperationException} will be
1.313 + * thrown from the attempted lookup. The exact class will be one of
1.314 + * the following:
1.315 + * <ul>
1.316 + * <li>NoSuchMethodException — if a method is requested but does not exist
1.317 + * <li>NoSuchFieldException — if a field is requested but does not exist
1.318 + * <li>IllegalAccessException — if the member exists but an access check fails
1.319 + * </ul>
1.320 + * <p>
1.321 + * In general, the conditions under which a method handle may be
1.322 + * looked up for a method {@code M} are no more restrictive than the conditions
1.323 + * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
1.324 + * Where the JVM would raise exceptions like {@code NoSuchMethodError},
1.325 + * a method handle lookup will generally raise a corresponding
1.326 + * checked exception, such as {@code NoSuchMethodException}.
1.327 + * And the effect of invoking the method handle resulting from the lookup
1.328 + * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
1.329 + * to executing the compiled, verified, and resolved call to {@code M}.
1.330 + * The same point is true of fields and constructors.
1.331 + * <p style="font-size:smaller;">
1.332 + * <em>Discussion:</em>
1.333 + * Access checks only apply to named and reflected methods,
1.334 + * constructors, and fields.
1.335 + * Other method handle creation methods, such as
1.336 + * {@link MethodHandle#asType MethodHandle.asType},
1.337 + * do not require any access checks, and are used
1.338 + * independently of any {@code Lookup} object.
1.339 + * <p>
1.340 + * If the desired member is {@code protected}, the usual JVM rules apply,
1.341 + * including the requirement that the lookup class must be either be in the
1.342 + * same package as the desired member, or must inherit that member.
1.343 + * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
1.344 + * In addition, if the desired member is a non-static field or method
1.345 + * in a different package, the resulting method handle may only be applied
1.346 + * to objects of the lookup class or one of its subclasses.
1.347 + * This requirement is enforced by narrowing the type of the leading
1.348 + * {@code this} parameter from {@code C}
1.349 + * (which will necessarily be a superclass of the lookup class)
1.350 + * to the lookup class itself.
1.351 + * <p>
1.352 + * The JVM imposes a similar requirement on {@code invokespecial} instruction,
1.353 + * that the receiver argument must match both the resolved method <em>and</em>
1.354 + * the current class. Again, this requirement is enforced by narrowing the
1.355 + * type of the leading parameter to the resulting method handle.
1.356 + * (See the Java Virtual Machine Specification, section 4.10.1.9.)
1.357 + * <p>
1.358 + * The JVM represents constructors and static initializer blocks as internal methods
1.359 + * with special names ({@code "<init>"} and {@code "<clinit>"}).
1.360 + * The internal syntax of invocation instructions allows them to refer to such internal
1.361 + * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
1.362 + * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
1.363 + * <p>
1.364 + * In some cases, access between nested classes is obtained by the Java compiler by creating
1.365 + * an wrapper method to access a private method of another class
1.366 + * in the same top-level declaration.
1.367 + * For example, a nested class {@code C.D}
1.368 + * can access private members within other related classes such as
1.369 + * {@code C}, {@code C.D.E}, or {@code C.B},
1.370 + * but the Java compiler may need to generate wrapper methods in
1.371 + * those related classes. In such cases, a {@code Lookup} object on
1.372 + * {@code C.E} would be unable to those private members.
1.373 + * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
1.374 + * which can transform a lookup on {@code C.E} into one on any of those other
1.375 + * classes, without special elevation of privilege.
1.376 + * <p>
1.377 + * The accesses permitted to a given lookup object may be limited,
1.378 + * according to its set of {@link #lookupModes lookupModes},
1.379 + * to a subset of members normally accessible to the lookup class.
1.380 + * For example, the {@link MethodHandles#publicLookup publicLookup}
1.381 + * method produces a lookup object which is only allowed to access
1.382 + * public members in public classes.
1.383 + * The caller sensitive method {@link MethodHandles#lookup lookup}
1.384 + * produces a lookup object with full capabilities relative to
1.385 + * its caller class, to emulate all supported bytecode behaviors.
1.386 + * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
1.387 + * with fewer access modes than the original lookup object.
1.388 + *
1.389 + * <p style="font-size:smaller;">
1.390 + * <a name="privacc"></a>
1.391 + * <em>Discussion of private access:</em>
1.392 + * We say that a lookup has <em>private access</em>
1.393 + * if its {@linkplain #lookupModes lookup modes}
1.394 + * include the possibility of accessing {@code private} members.
1.395 + * As documented in the relevant methods elsewhere,
1.396 + * only lookups with private access possess the following capabilities:
1.397 + * <ul style="font-size:smaller;">
1.398 + * <li>access private fields, methods, and constructors of the lookup class
1.399 + * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
1.400 + * such as {@code Class.forName}
1.401 + * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
1.402 + * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
1.403 + * for classes accessible to the lookup class
1.404 + * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
1.405 + * within the same package member
1.406 + * </ul>
1.407 + * <p style="font-size:smaller;">
1.408 + * Each of these permissions is a consequence of the fact that a lookup object
1.409 + * with private access can be securely traced back to an originating class,
1.410 + * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
1.411 + * can be reliably determined and emulated by method handles.
1.412 + *
1.413 + * <h1><a name="secmgr"></a>Security manager interactions</h1>
1.414 + * Although bytecode instructions can only refer to classes in
1.415 + * a related class loader, this API can search for methods in any
1.416 + * class, as long as a reference to its {@code Class} object is
1.417 + * available. Such cross-loader references are also possible with the
1.418 + * Core Reflection API, and are impossible to bytecode instructions
1.419 + * such as {@code invokestatic} or {@code getfield}.
1.420 + * There is a {@linkplain java.lang.SecurityManager security manager API}
1.421 + * to allow applications to check such cross-loader references.
1.422 + * These checks apply to both the {@code MethodHandles.Lookup} API
1.423 + * and the Core Reflection API
1.424 + * (as found on {@link java.lang.Class Class}).
1.425 + * <p>
1.426 + * If a security manager is present, member lookups are subject to
1.427 + * additional checks.
1.428 + * From one to three calls are made to the security manager.
1.429 + * Any of these calls can refuse access by throwing a
1.430 + * {@link java.lang.SecurityException SecurityException}.
1.431 + * Define {@code smgr} as the security manager,
1.432 + * {@code lookc} as the lookup class of the current lookup object,
1.433 + * {@code refc} as the containing class in which the member
1.434 + * is being sought, and {@code defc} as the class in which the
1.435 + * member is actually defined.
1.436 + * The value {@code lookc} is defined as <em>not present</em>
1.437 + * if the current lookup object does not have
1.438 + * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1.439 + * The calls are made according to the following rules:
1.440 + * <ul>
1.441 + * <li><b>Step 1:</b>
1.442 + * If {@code lookc} is not present, or if its class loader is not
1.443 + * the same as or an ancestor of the class loader of {@code refc},
1.444 + * then {@link SecurityManager#checkPackageAccess
1.445 + * smgr.checkPackageAccess(refcPkg)} is called,
1.446 + * where {@code refcPkg} is the package of {@code refc}.
1.447 + * <li><b>Step 2:</b>
1.448 + * If the retrieved member is not public and
1.449 + * {@code lookc} is not present, then
1.450 + * {@link SecurityManager#checkPermission smgr.checkPermission}
1.451 + * with {@code RuntimePermission("accessDeclaredMembers")} is called.
1.452 + * <li><b>Step 3:</b>
1.453 + * If the retrieved member is not public,
1.454 + * and if {@code lookc} is not present,
1.455 + * and if {@code defc} and {@code refc} are different,
1.456 + * then {@link SecurityManager#checkPackageAccess
1.457 + * smgr.checkPackageAccess(defcPkg)} is called,
1.458 + * where {@code defcPkg} is the package of {@code defc}.
1.459 + * </ul>
1.460 + * Security checks are performed after other access checks have passed.
1.461 + * Therefore, the above rules presuppose a member that is public,
1.462 + * or else that is being accessed from a lookup class that has
1.463 + * rights to access the member.
1.464 + *
1.465 + * <h1><a name="callsens"></a>Caller sensitive methods</h1>
1.466 + * A small number of Java methods have a special property called caller sensitivity.
1.467 + * A <em>caller-sensitive</em> method can behave differently depending on the
1.468 + * identity of its immediate caller.
1.469 + * <p>
1.470 + * If a method handle for a caller-sensitive method is requested,
1.471 + * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1.472 + * but they take account of the lookup class in a special way.
1.473 + * The resulting method handle behaves as if it were called
1.474 + * from an instruction contained in the lookup class,
1.475 + * so that the caller-sensitive method detects the lookup class.
1.476 + * (By contrast, the invoker of the method handle is disregarded.)
1.477 + * Thus, in the case of caller-sensitive methods,
1.478 + * different lookup classes may give rise to
1.479 + * differently behaving method handles.
1.480 + * <p>
1.481 + * In cases where the lookup object is
1.482 + * {@link MethodHandles#publicLookup() publicLookup()},
1.483 + * or some other lookup object without
1.484 + * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
1.485 + * the lookup class is disregarded.
1.486 + * In such cases, no caller-sensitive method handle can be created,
1.487 + * access is forbidden, and the lookup fails with an
1.488 + * {@code IllegalAccessException}.
1.489 + * <p style="font-size:smaller;">
1.490 + * <em>Discussion:</em>
1.491 + * For example, the caller-sensitive method
1.492 + * {@link java.lang.Class#forName(String) Class.forName(x)}
1.493 + * can return varying classes or throw varying exceptions,
1.494 + * depending on the class loader of the class that calls it.
1.495 + * A public lookup of {@code Class.forName} will fail, because
1.496 + * there is no reasonable way to determine its bytecode behavior.
1.497 + * <p style="font-size:smaller;">
1.498 + * If an application caches method handles for broad sharing,
1.499 + * it should use {@code publicLookup()} to create them.
1.500 + * If there is a lookup of {@code Class.forName}, it will fail,
1.501 + * and the application must take appropriate action in that case.
1.502 + * It may be that a later lookup, perhaps during the invocation of a
1.503 + * bootstrap method, can incorporate the specific identity
1.504 + * of the caller, making the method accessible.
1.505 + * <p style="font-size:smaller;">
1.506 + * The function {@code MethodHandles.lookup} is caller sensitive
1.507 + * so that there can be a secure foundation for lookups.
1.508 + * Nearly all other methods in the JSR 292 API rely on lookup
1.509 + * objects to check access requests.
1.510 + */
1.511 + public static final
1.512 + class Lookup {
1.513 + /** The class on behalf of whom the lookup is being performed. */
1.514 + private final Class<?> lookupClass;
1.515 +
1.516 + /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1.517 + private final int allowedModes;
1.518 +
1.519 + /** A single-bit mask representing {@code public} access,
1.520 + * which may contribute to the result of {@link #lookupModes lookupModes}.
1.521 + * The value, {@code 0x01}, happens to be the same as the value of the
1.522 + * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1.523 + */
1.524 + public static final int PUBLIC = Modifier.PUBLIC;
1.525 +
1.526 + /** A single-bit mask representing {@code private} access,
1.527 + * which may contribute to the result of {@link #lookupModes lookupModes}.
1.528 + * The value, {@code 0x02}, happens to be the same as the value of the
1.529 + * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1.530 + */
1.531 + public static final int PRIVATE = Modifier.PRIVATE;
1.532 +
1.533 + /** A single-bit mask representing {@code protected} access,
1.534 + * which may contribute to the result of {@link #lookupModes lookupModes}.
1.535 + * The value, {@code 0x04}, happens to be the same as the value of the
1.536 + * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1.537 + */
1.538 + public static final int PROTECTED = Modifier.PROTECTED;
1.539 +
1.540 + /** A single-bit mask representing {@code package} access (default access),
1.541 + * which may contribute to the result of {@link #lookupModes lookupModes}.
1.542 + * The value is {@code 0x08}, which does not correspond meaningfully to
1.543 + * any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1.544 + */
1.545 + public static final int PACKAGE = Modifier.STATIC;
1.546 +
1.547 + private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE);
1.548 + private static final int TRUSTED = -1;
1.549 +
1.550 + private static int fixmods(int mods) {
1.551 + mods &= (ALL_MODES - PACKAGE);
1.552 + return (mods != 0) ? mods : PACKAGE;
1.553 + }
1.554 +
1.555 + /** Tells which class is performing the lookup. It is this class against
1.556 + * which checks are performed for visibility and access permissions.
1.557 + * <p>
1.558 + * The class implies a maximum level of access permission,
1.559 + * but the permissions may be additionally limited by the bitmask
1.560 + * {@link #lookupModes lookupModes}, which controls whether non-public members
1.561 + * can be accessed.
1.562 + * @return the lookup class, on behalf of which this lookup object finds members
1.563 + */
1.564 + public Class<?> lookupClass() {
1.565 + return lookupClass;
1.566 + }
1.567 +
1.568 + // This is just for calling out to MethodHandleImpl.
1.569 + private Class<?> lookupClassOrNull() {
1.570 + return (allowedModes == TRUSTED) ? null : lookupClass;
1.571 + }
1.572 +
1.573 + /** Tells which access-protection classes of members this lookup object can produce.
1.574 + * The result is a bit-mask of the bits
1.575 + * {@linkplain #PUBLIC PUBLIC (0x01)},
1.576 + * {@linkplain #PRIVATE PRIVATE (0x02)},
1.577 + * {@linkplain #PROTECTED PROTECTED (0x04)},
1.578 + * and {@linkplain #PACKAGE PACKAGE (0x08)}.
1.579 + * <p>
1.580 + * A freshly-created lookup object
1.581 + * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
1.582 + * has all possible bits set, since the caller class can access all its own members.
1.583 + * A lookup object on a new lookup class
1.584 + * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1.585 + * may have some mode bits set to zero.
1.586 + * The purpose of this is to restrict access via the new lookup object,
1.587 + * so that it can access only names which can be reached by the original
1.588 + * lookup object, and also by the new lookup class.
1.589 + * @return the lookup modes, which limit the kinds of access performed by this lookup object
1.590 + */
1.591 + public int lookupModes() {
1.592 + return allowedModes & ALL_MODES;
1.593 + }
1.594 +
1.595 + /** Embody the current class (the lookupClass) as a lookup class
1.596 + * for method handle creation.
1.597 + * Must be called by from a method in this package,
1.598 + * which in turn is called by a method not in this package.
1.599 + */
1.600 + Lookup(Class<?> lookupClass) {
1.601 + this(lookupClass, ALL_MODES);
1.602 + // make sure we haven't accidentally picked up a privileged class:
1.603 + checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
1.604 + }
1.605 +
1.606 + private Lookup(Class<?> lookupClass, int allowedModes) {
1.607 + this.lookupClass = lookupClass;
1.608 + this.allowedModes = allowedModes;
1.609 + }
1.610 +
1.611 + /**
1.612 + * Creates a lookup on the specified new lookup class.
1.613 + * The resulting object will report the specified
1.614 + * class as its own {@link #lookupClass lookupClass}.
1.615 + * <p>
1.616 + * However, the resulting {@code Lookup} object is guaranteed
1.617 + * to have no more access capabilities than the original.
1.618 + * In particular, access capabilities can be lost as follows:<ul>
1.619 + * <li>If the new lookup class differs from the old one,
1.620 + * protected members will not be accessible by virtue of inheritance.
1.621 + * (Protected members may continue to be accessible because of package sharing.)
1.622 + * <li>If the new lookup class is in a different package
1.623 + * than the old one, protected and default (package) members will not be accessible.
1.624 + * <li>If the new lookup class is not within the same package member
1.625 + * as the old one, private members will not be accessible.
1.626 + * <li>If the new lookup class is not accessible to the old lookup class,
1.627 + * then no members, not even public members, will be accessible.
1.628 + * (In all other cases, public members will continue to be accessible.)
1.629 + * </ul>
1.630 + *
1.631 + * @param requestedLookupClass the desired lookup class for the new lookup object
1.632 + * @return a lookup object which reports the desired lookup class
1.633 + * @throws NullPointerException if the argument is null
1.634 + */
1.635 + public Lookup in(Class<?> requestedLookupClass) {
1.636 + requestedLookupClass.getClass(); // null check
1.637 + if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all
1.638 + return new Lookup(requestedLookupClass, ALL_MODES);
1.639 + if (requestedLookupClass == this.lookupClass)
1.640 + return this; // keep same capabilities
1.641 + int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
1.642 + if ((newModes & PACKAGE) != 0
1.643 + && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1.644 + newModes &= ~(PACKAGE|PRIVATE);
1.645 + }
1.646 + // Allow nestmate lookups to be created without special privilege:
1.647 + if ((newModes & PRIVATE) != 0
1.648 + && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1.649 + newModes &= ~PRIVATE;
1.650 + }
1.651 + if ((newModes & PUBLIC) != 0
1.652 + && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
1.653 + // The requested class it not accessible from the lookup class.
1.654 + // No permissions.
1.655 + newModes = 0;
1.656 + }
1.657 + checkUnprivilegedlookupClass(requestedLookupClass, newModes);
1.658 + return new Lookup(requestedLookupClass, newModes);
1.659 + }
1.660 +
1.661 + // Make sure outer class is initialized first.
1.662 + static { IMPL_NAMES.getClass(); }
1.663 +
1.664 + /** Version of lookup which is trusted minimally.
1.665 + * It can only be used to create method handles to
1.666 + * publicly accessible members.
1.667 + */
1.668 + static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC);
1.669 +
1.670 + /** Package-private version of lookup which is trusted. */
1.671 + static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
1.672 +
1.673 + private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
1.674 + String name = lookupClass.getName();
1.675 + if (name.startsWith("java.lang.invoke."))
1.676 + throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
1.677 +
1.678 + // For caller-sensitive MethodHandles.lookup()
1.679 + // disallow lookup more restricted packages
1.680 + if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
1.681 + if (name.startsWith("java.") ||
1.682 + (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
1.683 + throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
1.684 + }
1.685 + }
1.686 + }
1.687 +
1.688 + /**
1.689 + * Displays the name of the class from which lookups are to be made.
1.690 + * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
1.691 + * If there are restrictions on the access permitted to this lookup,
1.692 + * this is indicated by adding a suffix to the class name, consisting
1.693 + * of a slash and a keyword. The keyword represents the strongest
1.694 + * allowed access, and is chosen as follows:
1.695 + * <ul>
1.696 + * <li>If no access is allowed, the suffix is "/noaccess".
1.697 + * <li>If only public access is allowed, the suffix is "/public".
1.698 + * <li>If only public and package access are allowed, the suffix is "/package".
1.699 + * <li>If only public, package, and private access are allowed, the suffix is "/private".
1.700 + * </ul>
1.701 + * If none of the above cases apply, it is the case that full
1.702 + * access (public, package, private, and protected) is allowed.
1.703 + * In this case, no suffix is added.
1.704 + * This is true only of an object obtained originally from
1.705 + * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
1.706 + * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
1.707 + * always have restricted access, and will display a suffix.
1.708 + * <p>
1.709 + * (It may seem strange that protected access should be
1.710 + * stronger than private access. Viewed independently from
1.711 + * package access, protected access is the first to be lost,
1.712 + * because it requires a direct subclass relationship between
1.713 + * caller and callee.)
1.714 + * @see #in
1.715 + */
1.716 + @Override
1.717 + public String toString() {
1.718 + String cname = lookupClass.getName();
1.719 + switch (allowedModes) {
1.720 + case 0: // no privileges
1.721 + return cname + "/noaccess";
1.722 + case PUBLIC:
1.723 + return cname + "/public";
1.724 + case PUBLIC|PACKAGE:
1.725 + return cname + "/package";
1.726 + case ALL_MODES & ~PROTECTED:
1.727 + return cname + "/private";
1.728 + case ALL_MODES:
1.729 + return cname;
1.730 + case TRUSTED:
1.731 + return "/trusted"; // internal only; not exported
1.732 + default: // Should not happen, but it's a bitfield...
1.733 + cname = cname + "/" + Integer.toHexString(allowedModes);
1.734 + assert(false) : cname;
1.735 + return cname;
1.736 + }
1.737 + }
1.738 +
1.739 + /**
1.740 + * Produces a method handle for a static method.
1.741 + * The type of the method handle will be that of the method.
1.742 + * (Since static methods do not take receivers, there is no
1.743 + * additional receiver argument inserted into the method handle type,
1.744 + * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
1.745 + * The method and all its argument types must be accessible to the lookup object.
1.746 + * <p>
1.747 + * The returned method handle will have
1.748 + * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1.749 + * the method's variable arity modifier bit ({@code 0x0080}) is set.
1.750 + * <p>
1.751 + * If the returned method handle is invoked, the method's class will
1.752 + * be initialized, if it has not already been initialized.
1.753 + * <p><b>Example:</b>
1.754 + * <blockquote><pre>{@code
1.755 +import static java.lang.invoke.MethodHandles.*;
1.756 +import static java.lang.invoke.MethodType.*;
1.757 +...
1.758 +MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
1.759 + "asList", methodType(List.class, Object[].class));
1.760 +assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
1.761 + * }</pre></blockquote>
1.762 + * @param refc the class from which the method is accessed
1.763 + * @param name the name of the method
1.764 + * @param type the type of the method
1.765 + * @return the desired method handle
1.766 + * @throws NoSuchMethodException if the method does not exist
1.767 + * @throws IllegalAccessException if access checking fails,
1.768 + * or if the method is not {@code static},
1.769 + * or if the method's variable arity modifier bit
1.770 + * is set and {@code asVarargsCollector} fails
1.771 + * @exception SecurityException if a security manager is present and it
1.772 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.773 + * @throws NullPointerException if any argument is null
1.774 + */
1.775 + public
1.776 + MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1.777 + MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
1.778 + return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
1.779 + }
1.780 +
1.781 + /**
1.782 + * Produces a method handle for a virtual method.
1.783 + * The type of the method handle will be that of the method,
1.784 + * with the receiver type (usually {@code refc}) prepended.
1.785 + * The method and all its argument types must be accessible to the lookup object.
1.786 + * <p>
1.787 + * When called, the handle will treat the first argument as a receiver
1.788 + * and dispatch on the receiver's type to determine which method
1.789 + * implementation to enter.
1.790 + * (The dispatching action is identical with that performed by an
1.791 + * {@code invokevirtual} or {@code invokeinterface} instruction.)
1.792 + * <p>
1.793 + * The first argument will be of type {@code refc} if the lookup
1.794 + * class has full privileges to access the member. Otherwise
1.795 + * the member must be {@code protected} and the first argument
1.796 + * will be restricted in type to the lookup class.
1.797 + * <p>
1.798 + * The returned method handle will have
1.799 + * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1.800 + * the method's variable arity modifier bit ({@code 0x0080}) is set.
1.801 + * <p>
1.802 + * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
1.803 + * instructions and method handles produced by {@code findVirtual},
1.804 + * if the class is {@code MethodHandle} and the name string is
1.805 + * {@code invokeExact} or {@code invoke}, the resulting
1.806 + * method handle is equivalent to one produced by
1.807 + * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
1.808 + * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
1.809 + * with the same {@code type} argument.
1.810 + *
1.811 + * <b>Example:</b>
1.812 + * <blockquote><pre>{@code
1.813 +import static java.lang.invoke.MethodHandles.*;
1.814 +import static java.lang.invoke.MethodType.*;
1.815 +...
1.816 +MethodHandle MH_concat = publicLookup().findVirtual(String.class,
1.817 + "concat", methodType(String.class, String.class));
1.818 +MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
1.819 + "hashCode", methodType(int.class));
1.820 +MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
1.821 + "hashCode", methodType(int.class));
1.822 +assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
1.823 +assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
1.824 +assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
1.825 +// interface method:
1.826 +MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
1.827 + "subSequence", methodType(CharSequence.class, int.class, int.class));
1.828 +assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
1.829 +// constructor "internal method" must be accessed differently:
1.830 +MethodType MT_newString = methodType(void.class); //()V for new String()
1.831 +try { assertEquals("impossible", lookup()
1.832 + .findVirtual(String.class, "<init>", MT_newString));
1.833 + } catch (NoSuchMethodException ex) { } // OK
1.834 +MethodHandle MH_newString = publicLookup()
1.835 + .findConstructor(String.class, MT_newString);
1.836 +assertEquals("", (String) MH_newString.invokeExact());
1.837 + * }</pre></blockquote>
1.838 + *
1.839 + * @param refc the class or interface from which the method is accessed
1.840 + * @param name the name of the method
1.841 + * @param type the type of the method, with the receiver argument omitted
1.842 + * @return the desired method handle
1.843 + * @throws NoSuchMethodException if the method does not exist
1.844 + * @throws IllegalAccessException if access checking fails,
1.845 + * or if the method is {@code static}
1.846 + * or if the method's variable arity modifier bit
1.847 + * is set and {@code asVarargsCollector} fails
1.848 + * @exception SecurityException if a security manager is present and it
1.849 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.850 + * @throws NullPointerException if any argument is null
1.851 + */
1.852 + public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1.853 + if (refc == MethodHandle.class) {
1.854 + MethodHandle mh = findVirtualForMH(name, type);
1.855 + if (mh != null) return mh;
1.856 + }
1.857 + byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
1.858 + MemberName method = resolveOrFail(refKind, refc, name, type);
1.859 + return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
1.860 + }
1.861 + private MethodHandle findVirtualForMH(String name, MethodType type) {
1.862 + // these names require special lookups because of the implicit MethodType argument
1.863 + if ("invoke".equals(name))
1.864 + return invoker(type);
1.865 + if ("invokeExact".equals(name))
1.866 + return exactInvoker(type);
1.867 + assert(!MemberName.isMethodHandleInvokeName(name));
1.868 + return null;
1.869 + }
1.870 +
1.871 + /**
1.872 + * Produces a method handle which creates an object and initializes it, using
1.873 + * the constructor of the specified type.
1.874 + * The parameter types of the method handle will be those of the constructor,
1.875 + * while the return type will be a reference to the constructor's class.
1.876 + * The constructor and all its argument types must be accessible to the lookup object.
1.877 + * <p>
1.878 + * The requested type must have a return type of {@code void}.
1.879 + * (This is consistent with the JVM's treatment of constructor type descriptors.)
1.880 + * <p>
1.881 + * The returned method handle will have
1.882 + * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1.883 + * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1.884 + * <p>
1.885 + * If the returned method handle is invoked, the constructor's class will
1.886 + * be initialized, if it has not already been initialized.
1.887 + * <p><b>Example:</b>
1.888 + * <blockquote><pre>{@code
1.889 +import static java.lang.invoke.MethodHandles.*;
1.890 +import static java.lang.invoke.MethodType.*;
1.891 +...
1.892 +MethodHandle MH_newArrayList = publicLookup().findConstructor(
1.893 + ArrayList.class, methodType(void.class, Collection.class));
1.894 +Collection orig = Arrays.asList("x", "y");
1.895 +Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
1.896 +assert(orig != copy);
1.897 +assertEquals(orig, copy);
1.898 +// a variable-arity constructor:
1.899 +MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
1.900 + ProcessBuilder.class, methodType(void.class, String[].class));
1.901 +ProcessBuilder pb = (ProcessBuilder)
1.902 + MH_newProcessBuilder.invoke("x", "y", "z");
1.903 +assertEquals("[x, y, z]", pb.command().toString());
1.904 + * }</pre></blockquote>
1.905 + * @param refc the class or interface from which the method is accessed
1.906 + * @param type the type of the method, with the receiver argument omitted, and a void return type
1.907 + * @return the desired method handle
1.908 + * @throws NoSuchMethodException if the constructor does not exist
1.909 + * @throws IllegalAccessException if access checking fails
1.910 + * or if the method's variable arity modifier bit
1.911 + * is set and {@code asVarargsCollector} fails
1.912 + * @exception SecurityException if a security manager is present and it
1.913 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.914 + * @throws NullPointerException if any argument is null
1.915 + */
1.916 + public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1.917 + String name = "<init>";
1.918 + MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
1.919 + return getDirectConstructor(refc, ctor);
1.920 + }
1.921 +
1.922 + /**
1.923 + * Produces an early-bound method handle for a virtual method.
1.924 + * It will bypass checks for overriding methods on the receiver,
1.925 + * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1.926 + * instruction from within the explicitly specified {@code specialCaller}.
1.927 + * The type of the method handle will be that of the method,
1.928 + * with a suitably restricted receiver type prepended.
1.929 + * (The receiver type will be {@code specialCaller} or a subtype.)
1.930 + * The method and all its argument types must be accessible
1.931 + * to the lookup object.
1.932 + * <p>
1.933 + * Before method resolution,
1.934 + * if the explicitly specified caller class is not identical with the
1.935 + * lookup class, or if this lookup object does not have
1.936 + * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1.937 + * privileges, the access fails.
1.938 + * <p>
1.939 + * The returned method handle will have
1.940 + * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1.941 + * the method's variable arity modifier bit ({@code 0x0080}) is set.
1.942 + * <p style="font-size:smaller;">
1.943 + * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API,
1.944 + * even though the {@code invokespecial} instruction can refer to them
1.945 + * in special circumstances. Use {@link #findConstructor findConstructor}
1.946 + * to access instance initialization methods in a safe manner.)</em>
1.947 + * <p><b>Example:</b>
1.948 + * <blockquote><pre>{@code
1.949 +import static java.lang.invoke.MethodHandles.*;
1.950 +import static java.lang.invoke.MethodType.*;
1.951 +...
1.952 +static class Listie extends ArrayList {
1.953 + public String toString() { return "[wee Listie]"; }
1.954 + static Lookup lookup() { return MethodHandles.lookup(); }
1.955 +}
1.956 +...
1.957 +// no access to constructor via invokeSpecial:
1.958 +MethodHandle MH_newListie = Listie.lookup()
1.959 + .findConstructor(Listie.class, methodType(void.class));
1.960 +Listie l = (Listie) MH_newListie.invokeExact();
1.961 +try { assertEquals("impossible", Listie.lookup().findSpecial(
1.962 + Listie.class, "<init>", methodType(void.class), Listie.class));
1.963 + } catch (NoSuchMethodException ex) { } // OK
1.964 +// access to super and self methods via invokeSpecial:
1.965 +MethodHandle MH_super = Listie.lookup().findSpecial(
1.966 + ArrayList.class, "toString" , methodType(String.class), Listie.class);
1.967 +MethodHandle MH_this = Listie.lookup().findSpecial(
1.968 + Listie.class, "toString" , methodType(String.class), Listie.class);
1.969 +MethodHandle MH_duper = Listie.lookup().findSpecial(
1.970 + Object.class, "toString" , methodType(String.class), Listie.class);
1.971 +assertEquals("[]", (String) MH_super.invokeExact(l));
1.972 +assertEquals(""+l, (String) MH_this.invokeExact(l));
1.973 +assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
1.974 +try { assertEquals("inaccessible", Listie.lookup().findSpecial(
1.975 + String.class, "toString", methodType(String.class), Listie.class));
1.976 + } catch (IllegalAccessException ex) { } // OK
1.977 +Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
1.978 +assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
1.979 + * }</pre></blockquote>
1.980 + *
1.981 + * @param refc the class or interface from which the method is accessed
1.982 + * @param name the name of the method (which must not be "<init>")
1.983 + * @param type the type of the method, with the receiver argument omitted
1.984 + * @param specialCaller the proposed calling class to perform the {@code invokespecial}
1.985 + * @return the desired method handle
1.986 + * @throws NoSuchMethodException if the method does not exist
1.987 + * @throws IllegalAccessException if access checking fails
1.988 + * or if the method's variable arity modifier bit
1.989 + * is set and {@code asVarargsCollector} fails
1.990 + * @exception SecurityException if a security manager is present and it
1.991 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.992 + * @throws NullPointerException if any argument is null
1.993 + */
1.994 + public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
1.995 + Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
1.996 + checkSpecialCaller(specialCaller);
1.997 + Lookup specialLookup = this.in(specialCaller);
1.998 + MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
1.999 + return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1.1000 + }
1.1001 +
1.1002 + /**
1.1003 + * Produces a method handle giving read access to a non-static field.
1.1004 + * The type of the method handle will have a return type of the field's
1.1005 + * value type.
1.1006 + * The method handle's single argument will be the instance containing
1.1007 + * the field.
1.1008 + * Access checking is performed immediately on behalf of the lookup class.
1.1009 + * @param refc the class or interface from which the method is accessed
1.1010 + * @param name the field's name
1.1011 + * @param type the field's type
1.1012 + * @return a method handle which can load values from the field
1.1013 + * @throws NoSuchFieldException if the field does not exist
1.1014 + * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1.1015 + * @exception SecurityException if a security manager is present and it
1.1016 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.1017 + * @throws NullPointerException if any argument is null
1.1018 + */
1.1019 + public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1.1020 + MemberName field = resolveOrFail(REF_getField, refc, name, type);
1.1021 + return getDirectField(REF_getField, refc, field);
1.1022 + }
1.1023 +
1.1024 + /**
1.1025 + * Produces a method handle giving write access to a non-static field.
1.1026 + * The type of the method handle will have a void return type.
1.1027 + * The method handle will take two arguments, the instance containing
1.1028 + * the field, and the value to be stored.
1.1029 + * The second argument will be of the field's value type.
1.1030 + * Access checking is performed immediately on behalf of the lookup class.
1.1031 + * @param refc the class or interface from which the method is accessed
1.1032 + * @param name the field's name
1.1033 + * @param type the field's type
1.1034 + * @return a method handle which can store values into the field
1.1035 + * @throws NoSuchFieldException if the field does not exist
1.1036 + * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1.1037 + * @exception SecurityException if a security manager is present and it
1.1038 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.1039 + * @throws NullPointerException if any argument is null
1.1040 + */
1.1041 + public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1.1042 + MemberName field = resolveOrFail(REF_putField, refc, name, type);
1.1043 + return getDirectField(REF_putField, refc, field);
1.1044 + }
1.1045 +
1.1046 + /**
1.1047 + * Produces a method handle giving read access to a static field.
1.1048 + * The type of the method handle will have a return type of the field's
1.1049 + * value type.
1.1050 + * The method handle will take no arguments.
1.1051 + * Access checking is performed immediately on behalf of the lookup class.
1.1052 + * <p>
1.1053 + * If the returned method handle is invoked, the field's class will
1.1054 + * be initialized, if it has not already been initialized.
1.1055 + * @param refc the class or interface from which the method is accessed
1.1056 + * @param name the field's name
1.1057 + * @param type the field's type
1.1058 + * @return a method handle which can load values from the field
1.1059 + * @throws NoSuchFieldException if the field does not exist
1.1060 + * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1.1061 + * @exception SecurityException if a security manager is present and it
1.1062 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.1063 + * @throws NullPointerException if any argument is null
1.1064 + */
1.1065 + public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1.1066 + MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
1.1067 + return getDirectField(REF_getStatic, refc, field);
1.1068 + }
1.1069 +
1.1070 + /**
1.1071 + * Produces a method handle giving write access to a static field.
1.1072 + * The type of the method handle will have a void return type.
1.1073 + * The method handle will take a single
1.1074 + * argument, of the field's value type, the value to be stored.
1.1075 + * Access checking is performed immediately on behalf of the lookup class.
1.1076 + * <p>
1.1077 + * If the returned method handle is invoked, the field's class will
1.1078 + * be initialized, if it has not already been initialized.
1.1079 + * @param refc the class or interface from which the method is accessed
1.1080 + * @param name the field's name
1.1081 + * @param type the field's type
1.1082 + * @return a method handle which can store values into the field
1.1083 + * @throws NoSuchFieldException if the field does not exist
1.1084 + * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1.1085 + * @exception SecurityException if a security manager is present and it
1.1086 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.1087 + * @throws NullPointerException if any argument is null
1.1088 + */
1.1089 + public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1.1090 + MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
1.1091 + return getDirectField(REF_putStatic, refc, field);
1.1092 + }
1.1093 +
1.1094 + /**
1.1095 + * Produces an early-bound method handle for a non-static method.
1.1096 + * The receiver must have a supertype {@code defc} in which a method
1.1097 + * of the given name and type is accessible to the lookup class.
1.1098 + * The method and all its argument types must be accessible to the lookup object.
1.1099 + * The type of the method handle will be that of the method,
1.1100 + * without any insertion of an additional receiver parameter.
1.1101 + * The given receiver will be bound into the method handle,
1.1102 + * so that every call to the method handle will invoke the
1.1103 + * requested method on the given receiver.
1.1104 + * <p>
1.1105 + * The returned method handle will have
1.1106 + * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1.1107 + * the method's variable arity modifier bit ({@code 0x0080}) is set
1.1108 + * <em>and</em> the trailing array argument is not the only argument.
1.1109 + * (If the trailing array argument is the only argument,
1.1110 + * the given receiver value will be bound to it.)
1.1111 + * <p>
1.1112 + * This is equivalent to the following code:
1.1113 + * <blockquote><pre>{@code
1.1114 +import static java.lang.invoke.MethodHandles.*;
1.1115 +import static java.lang.invoke.MethodType.*;
1.1116 +...
1.1117 +MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1.1118 +MethodHandle mh1 = mh0.bindTo(receiver);
1.1119 +MethodType mt1 = mh1.type();
1.1120 +if (mh0.isVarargsCollector())
1.1121 + mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
1.1122 +return mh1;
1.1123 + * }</pre></blockquote>
1.1124 + * where {@code defc} is either {@code receiver.getClass()} or a super
1.1125 + * type of that class, in which the requested method is accessible
1.1126 + * to the lookup class.
1.1127 + * (Note that {@code bindTo} does not preserve variable arity.)
1.1128 + * @param receiver the object from which the method is accessed
1.1129 + * @param name the name of the method
1.1130 + * @param type the type of the method, with the receiver argument omitted
1.1131 + * @return the desired method handle
1.1132 + * @throws NoSuchMethodException if the method does not exist
1.1133 + * @throws IllegalAccessException if access checking fails
1.1134 + * or if the method's variable arity modifier bit
1.1135 + * is set and {@code asVarargsCollector} fails
1.1136 + * @exception SecurityException if a security manager is present and it
1.1137 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.1138 + * @throws NullPointerException if any argument is null
1.1139 + * @see MethodHandle#bindTo
1.1140 + * @see #findVirtual
1.1141 + */
1.1142 + public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1.1143 + Class<? extends Object> refc = receiver.getClass(); // may get NPE
1.1144 + MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
1.1145 + MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1.1146 + return mh.bindReceiver(receiver).setVarargs(method);
1.1147 + }
1.1148 +
1.1149 + /**
1.1150 + * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1.1151 + * to <i>m</i>, if the lookup class has permission.
1.1152 + * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
1.1153 + * If <i>m</i> is virtual, overriding is respected on every call.
1.1154 + * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
1.1155 + * The type of the method handle will be that of the method,
1.1156 + * with the receiver type prepended (but only if it is non-static).
1.1157 + * If the method's {@code accessible} flag is not set,
1.1158 + * access checking is performed immediately on behalf of the lookup class.
1.1159 + * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
1.1160 + * <p>
1.1161 + * The returned method handle will have
1.1162 + * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1.1163 + * the method's variable arity modifier bit ({@code 0x0080}) is set.
1.1164 + * <p>
1.1165 + * If <i>m</i> is static, and
1.1166 + * if the returned method handle is invoked, the method's class will
1.1167 + * be initialized, if it has not already been initialized.
1.1168 + * @param m the reflected method
1.1169 + * @return a method handle which can invoke the reflected method
1.1170 + * @throws IllegalAccessException if access checking fails
1.1171 + * or if the method's variable arity modifier bit
1.1172 + * is set and {@code asVarargsCollector} fails
1.1173 + * @throws NullPointerException if the argument is null
1.1174 + */
1.1175 + public MethodHandle unreflect(Method m) throws IllegalAccessException {
1.1176 + if (m.getDeclaringClass() == MethodHandle.class) {
1.1177 + MethodHandle mh = unreflectForMH(m);
1.1178 + if (mh != null) return mh;
1.1179 + }
1.1180 + MemberName method = new MemberName(m);
1.1181 + byte refKind = method.getReferenceKind();
1.1182 + if (refKind == REF_invokeSpecial)
1.1183 + refKind = REF_invokeVirtual;
1.1184 + assert(method.isMethod());
1.1185 + Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
1.1186 + return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
1.1187 + }
1.1188 + private MethodHandle unreflectForMH(Method m) {
1.1189 + // these names require special lookups because they throw UnsupportedOperationException
1.1190 + if (MemberName.isMethodHandleInvokeName(m.getName()))
1.1191 + return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
1.1192 + return null;
1.1193 + }
1.1194 +
1.1195 + /**
1.1196 + * Produces a method handle for a reflected method.
1.1197 + * It will bypass checks for overriding methods on the receiver,
1.1198 + * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1.1199 + * instruction from within the explicitly specified {@code specialCaller}.
1.1200 + * The type of the method handle will be that of the method,
1.1201 + * with a suitably restricted receiver type prepended.
1.1202 + * (The receiver type will be {@code specialCaller} or a subtype.)
1.1203 + * If the method's {@code accessible} flag is not set,
1.1204 + * access checking is performed immediately on behalf of the lookup class,
1.1205 + * as if {@code invokespecial} instruction were being linked.
1.1206 + * <p>
1.1207 + * Before method resolution,
1.1208 + * if the explicitly specified caller class is not identical with the
1.1209 + * lookup class, or if this lookup object does not have
1.1210 + * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1.1211 + * privileges, the access fails.
1.1212 + * <p>
1.1213 + * The returned method handle will have
1.1214 + * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1.1215 + * the method's variable arity modifier bit ({@code 0x0080}) is set.
1.1216 + * @param m the reflected method
1.1217 + * @param specialCaller the class nominally calling the method
1.1218 + * @return a method handle which can invoke the reflected method
1.1219 + * @throws IllegalAccessException if access checking fails
1.1220 + * or if the method's variable arity modifier bit
1.1221 + * is set and {@code asVarargsCollector} fails
1.1222 + * @throws NullPointerException if any argument is null
1.1223 + */
1.1224 + public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1.1225 + checkSpecialCaller(specialCaller);
1.1226 + Lookup specialLookup = this.in(specialCaller);
1.1227 + MemberName method = new MemberName(m, true);
1.1228 + assert(method.isMethod());
1.1229 + // ignore m.isAccessible: this is a new kind of access
1.1230 + return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
1.1231 + }
1.1232 +
1.1233 + /**
1.1234 + * Produces a method handle for a reflected constructor.
1.1235 + * The type of the method handle will be that of the constructor,
1.1236 + * with the return type changed to the declaring class.
1.1237 + * The method handle will perform a {@code newInstance} operation,
1.1238 + * creating a new instance of the constructor's class on the
1.1239 + * arguments passed to the method handle.
1.1240 + * <p>
1.1241 + * If the constructor's {@code accessible} flag is not set,
1.1242 + * access checking is performed immediately on behalf of the lookup class.
1.1243 + * <p>
1.1244 + * The returned method handle will have
1.1245 + * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1.1246 + * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1.1247 + * <p>
1.1248 + * If the returned method handle is invoked, the constructor's class will
1.1249 + * be initialized, if it has not already been initialized.
1.1250 + * @param c the reflected constructor
1.1251 + * @return a method handle which can invoke the reflected constructor
1.1252 + * @throws IllegalAccessException if access checking fails
1.1253 + * or if the method's variable arity modifier bit
1.1254 + * is set and {@code asVarargsCollector} fails
1.1255 + * @throws NullPointerException if the argument is null
1.1256 + */
1.1257 + public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
1.1258 + MemberName ctor = new MemberName(c);
1.1259 + assert(ctor.isConstructor());
1.1260 + Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
1.1261 + return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
1.1262 + }
1.1263 +
1.1264 + /**
1.1265 + * Produces a method handle giving read access to a reflected field.
1.1266 + * The type of the method handle will have a return type of the field's
1.1267 + * value type.
1.1268 + * If the field is static, the method handle will take no arguments.
1.1269 + * Otherwise, its single argument will be the instance containing
1.1270 + * the field.
1.1271 + * If the field's {@code accessible} flag is not set,
1.1272 + * access checking is performed immediately on behalf of the lookup class.
1.1273 + * <p>
1.1274 + * If the field is static, and
1.1275 + * if the returned method handle is invoked, the field's class will
1.1276 + * be initialized, if it has not already been initialized.
1.1277 + * @param f the reflected field
1.1278 + * @return a method handle which can load values from the reflected field
1.1279 + * @throws IllegalAccessException if access checking fails
1.1280 + * @throws NullPointerException if the argument is null
1.1281 + */
1.1282 + public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
1.1283 + return unreflectField(f, false);
1.1284 + }
1.1285 + private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
1.1286 + MemberName field = new MemberName(f, isSetter);
1.1287 + assert(isSetter
1.1288 + ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
1.1289 + : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
1.1290 + Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
1.1291 + return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
1.1292 + }
1.1293 +
1.1294 + /**
1.1295 + * Produces a method handle giving write access to a reflected field.
1.1296 + * The type of the method handle will have a void return type.
1.1297 + * If the field is static, the method handle will take a single
1.1298 + * argument, of the field's value type, the value to be stored.
1.1299 + * Otherwise, the two arguments will be the instance containing
1.1300 + * the field, and the value to be stored.
1.1301 + * If the field's {@code accessible} flag is not set,
1.1302 + * access checking is performed immediately on behalf of the lookup class.
1.1303 + * <p>
1.1304 + * If the field is static, and
1.1305 + * if the returned method handle is invoked, the field's class will
1.1306 + * be initialized, if it has not already been initialized.
1.1307 + * @param f the reflected field
1.1308 + * @return a method handle which can store values into the reflected field
1.1309 + * @throws IllegalAccessException if access checking fails
1.1310 + * @throws NullPointerException if the argument is null
1.1311 + */
1.1312 + public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
1.1313 + return unreflectField(f, true);
1.1314 + }
1.1315 +
1.1316 + /**
1.1317 + * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1.1318 + * created by this lookup object or a similar one.
1.1319 + * Security and access checks are performed to ensure that this lookup object
1.1320 + * is capable of reproducing the target method handle.
1.1321 + * This means that the cracking may fail if target is a direct method handle
1.1322 + * but was created by an unrelated lookup object.
1.1323 + * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
1.1324 + * and was created by a lookup object for a different class.
1.1325 + * @param target a direct method handle to crack into symbolic reference components
1.1326 + * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
1.1327 + * @exception SecurityException if a security manager is present and it
1.1328 + * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1.1329 + * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
1.1330 + * @exception NullPointerException if the target is {@code null}
1.1331 + * @see MethodHandleInfo
1.1332 + * @since 1.8
1.1333 + */
1.1334 + public MethodHandleInfo revealDirect(MethodHandle target) {
1.1335 + MemberName member = target.internalMemberName();
1.1336 + if (member == null || (!member.isResolved() && !member.isMethodHandleInvoke()))
1.1337 + throw newIllegalArgumentException("not a direct method handle");
1.1338 + Class<?> defc = member.getDeclaringClass();
1.1339 + byte refKind = member.getReferenceKind();
1.1340 + assert(MethodHandleNatives.refKindIsValid(refKind));
1.1341 + if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
1.1342 + // Devirtualized method invocation is usually formally virtual.
1.1343 + // To avoid creating extra MemberName objects for this common case,
1.1344 + // we encode this extra degree of freedom using MH.isInvokeSpecial.
1.1345 + refKind = REF_invokeVirtual;
1.1346 + if (refKind == REF_invokeVirtual && defc.isInterface())
1.1347 + // Symbolic reference is through interface but resolves to Object method (toString, etc.)
1.1348 + refKind = REF_invokeInterface;
1.1349 + // Check SM permissions and member access before cracking.
1.1350 + try {
1.1351 + checkAccess(refKind, defc, member);
1.1352 + checkSecurityManager(defc, member);
1.1353 + } catch (IllegalAccessException ex) {
1.1354 + throw new IllegalArgumentException(ex);
1.1355 + }
1.1356 + if (allowedModes != TRUSTED && member.isCallerSensitive()) {
1.1357 + Class<?> callerClass = target.internalCallerClass();
1.1358 + if (!hasPrivateAccess() || callerClass != lookupClass())
1.1359 + throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
1.1360 + }
1.1361 + // Produce the handle to the results.
1.1362 + return new InfoFromMemberName(this, member, refKind);
1.1363 + }
1.1364 +
1.1365 + /// Helper methods, all package-private.
1.1366 +
1.1367 + MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1.1368 + checkSymbolicClass(refc); // do this before attempting to resolve
1.1369 + name.getClass(); // NPE
1.1370 + type.getClass(); // NPE
1.1371 + return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1.1372 + NoSuchFieldException.class);
1.1373 + }
1.1374 +
1.1375 + MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1.1376 + checkSymbolicClass(refc); // do this before attempting to resolve
1.1377 + name.getClass(); // NPE
1.1378 + type.getClass(); // NPE
1.1379 + checkMethodName(refKind, name); // NPE check on name
1.1380 + return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1.1381 + NoSuchMethodException.class);
1.1382 + }
1.1383 +
1.1384 + MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
1.1385 + checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve
1.1386 + member.getName().getClass(); // NPE
1.1387 + member.getType().getClass(); // NPE
1.1388 + return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
1.1389 + ReflectiveOperationException.class);
1.1390 + }
1.1391 +
1.1392 + void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
1.1393 + refc.getClass(); // NPE
1.1394 + Class<?> caller = lookupClassOrNull();
1.1395 + if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
1.1396 + throw new MemberName(refc).makeAccessException("symbolic reference class is not public", this);
1.1397 + }
1.1398 +
1.1399 + /** Check name for an illegal leading "<" character. */
1.1400 + void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
1.1401 + if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
1.1402 + throw new NoSuchMethodException("illegal method name: "+name);
1.1403 + }
1.1404 +
1.1405 +
1.1406 + /**
1.1407 + * Find my trustable caller class if m is a caller sensitive method.
1.1408 + * If this lookup object has private access, then the caller class is the lookupClass.
1.1409 + * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
1.1410 + */
1.1411 + Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
1.1412 + Class<?> callerClass = null;
1.1413 + if (MethodHandleNatives.isCallerSensitive(m)) {
1.1414 + // Only lookups with private access are allowed to resolve caller-sensitive methods
1.1415 + if (hasPrivateAccess()) {
1.1416 + callerClass = lookupClass;
1.1417 + } else {
1.1418 + throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
1.1419 + }
1.1420 + }
1.1421 + return callerClass;
1.1422 + }
1.1423 +
1.1424 + private boolean hasPrivateAccess() {
1.1425 + return (allowedModes & PRIVATE) != 0;
1.1426 + }
1.1427 +
1.1428 + /**
1.1429 + * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
1.1430 + * Determines a trustable caller class to compare with refc, the symbolic reference class.
1.1431 + * If this lookup object has private access, then the caller class is the lookupClass.
1.1432 + */
1.1433 + void checkSecurityManager(Class<?> refc, MemberName m) {
1.1434 + SecurityManager smgr = System.getSecurityManager();
1.1435 + if (smgr == null) return;
1.1436 + if (allowedModes == TRUSTED) return;
1.1437 +
1.1438 + // Step 1:
1.1439 + boolean fullPowerLookup = hasPrivateAccess();
1.1440 + if (!fullPowerLookup ||
1.1441 + !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1.1442 + ReflectUtil.checkPackageAccess(refc);
1.1443 + }
1.1444 +
1.1445 + // Step 2:
1.1446 + if (m.isPublic()) return;
1.1447 + if (!fullPowerLookup) {
1.1448 + smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
1.1449 + }
1.1450 +
1.1451 + // Step 3:
1.1452 + Class<?> defc = m.getDeclaringClass();
1.1453 + if (!fullPowerLookup && defc != refc) {
1.1454 + ReflectUtil.checkPackageAccess(defc);
1.1455 + }
1.1456 + }
1.1457 +
1.1458 + void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1.1459 + boolean wantStatic = (refKind == REF_invokeStatic);
1.1460 + String message;
1.1461 + if (m.isConstructor())
1.1462 + message = "expected a method, not a constructor";
1.1463 + else if (!m.isMethod())
1.1464 + message = "expected a method";
1.1465 + else if (wantStatic != m.isStatic())
1.1466 + message = wantStatic ? "expected a static method" : "expected a non-static method";
1.1467 + else
1.1468 + { checkAccess(refKind, refc, m); return; }
1.1469 + throw m.makeAccessException(message, this);
1.1470 + }
1.1471 +
1.1472 + void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1.1473 + boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
1.1474 + String message;
1.1475 + if (wantStatic != m.isStatic())
1.1476 + message = wantStatic ? "expected a static field" : "expected a non-static field";
1.1477 + else
1.1478 + { checkAccess(refKind, refc, m); return; }
1.1479 + throw m.makeAccessException(message, this);
1.1480 + }
1.1481 +
1.1482 + /** Check public/protected/private bits on the symbolic reference class and its member. */
1.1483 + void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1.1484 + assert(m.referenceKindIsConsistentWith(refKind) &&
1.1485 + MethodHandleNatives.refKindIsValid(refKind) &&
1.1486 + (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
1.1487 + int allowedModes = this.allowedModes;
1.1488 + if (allowedModes == TRUSTED) return;
1.1489 + int mods = m.getModifiers();
1.1490 + if (Modifier.isProtected(mods) &&
1.1491 + refKind == REF_invokeVirtual &&
1.1492 + m.getDeclaringClass() == Object.class &&
1.1493 + m.getName().equals("clone") &&
1.1494 + refc.isArray()) {
1.1495 + // The JVM does this hack also.
1.1496 + // (See ClassVerifier::verify_invoke_instructions
1.1497 + // and LinkResolver::check_method_accessability.)
1.1498 + // Because the JVM does not allow separate methods on array types,
1.1499 + // there is no separate method for int[].clone.
1.1500 + // All arrays simply inherit Object.clone.
1.1501 + // But for access checking logic, we make Object.clone
1.1502 + // (normally protected) appear to be public.
1.1503 + // Later on, when the DirectMethodHandle is created,
1.1504 + // its leading argument will be restricted to the
1.1505 + // requested array type.
1.1506 + // N.B. The return type is not adjusted, because
1.1507 + // that is *not* the bytecode behavior.
1.1508 + mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
1.1509 + }
1.1510 + if (Modifier.isFinal(mods) &&
1.1511 + MethodHandleNatives.refKindIsSetter(refKind))
1.1512 + throw m.makeAccessException("unexpected set of a final field", this);
1.1513 + if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0)
1.1514 + return; // common case
1.1515 + int requestedModes = fixmods(mods); // adjust 0 => PACKAGE
1.1516 + if ((requestedModes & allowedModes) != 0) {
1.1517 + if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
1.1518 + mods, lookupClass(), allowedModes))
1.1519 + return;
1.1520 + } else {
1.1521 + // Protected members can also be checked as if they were package-private.
1.1522 + if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
1.1523 + && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
1.1524 + return;
1.1525 + }
1.1526 + throw m.makeAccessException(accessFailedMessage(refc, m), this);
1.1527 + }
1.1528 +
1.1529 + String accessFailedMessage(Class<?> refc, MemberName m) {
1.1530 + Class<?> defc = m.getDeclaringClass();
1.1531 + int mods = m.getModifiers();
1.1532 + // check the class first:
1.1533 + boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
1.1534 + (defc == refc ||
1.1535 + Modifier.isPublic(refc.getModifiers())));
1.1536 + if (!classOK && (allowedModes & PACKAGE) != 0) {
1.1537 + classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1.1538 + (defc == refc ||
1.1539 + VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1.1540 + }
1.1541 + if (!classOK)
1.1542 + return "class is not public";
1.1543 + if (Modifier.isPublic(mods))
1.1544 + return "access to public member failed"; // (how?)
1.1545 + if (Modifier.isPrivate(mods))
1.1546 + return "member is private";
1.1547 + if (Modifier.isProtected(mods))
1.1548 + return "member is protected";
1.1549 + return "member is private to package";
1.1550 + }
1.1551 +
1.1552 + private static final boolean ALLOW_NESTMATE_ACCESS = false;
1.1553 +
1.1554 + private void checkSpecialCaller(Class<?> specialCaller) throws IllegalAccessException {
1.1555 + int allowedModes = this.allowedModes;
1.1556 + if (allowedModes == TRUSTED) return;
1.1557 + if (!hasPrivateAccess()
1.1558 + || (specialCaller != lookupClass()
1.1559 + && !(ALLOW_NESTMATE_ACCESS &&
1.1560 + VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
1.1561 + throw new MemberName(specialCaller).
1.1562 + makeAccessException("no private access for invokespecial", this);
1.1563 + }
1.1564 +
1.1565 + private boolean restrictProtectedReceiver(MemberName method) {
1.1566 + // The accessing class only has the right to use a protected member
1.1567 + // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc.
1.1568 + if (!method.isProtected() || method.isStatic()
1.1569 + || allowedModes == TRUSTED
1.1570 + || method.getDeclaringClass() == lookupClass()
1.1571 + || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
1.1572 + || (ALLOW_NESTMATE_ACCESS &&
1.1573 + VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
1.1574 + return false;
1.1575 + return true;
1.1576 + }
1.1577 + private MethodHandle restrictReceiver(MemberName method, MethodHandle mh, Class<?> caller) throws IllegalAccessException {
1.1578 + assert(!method.isStatic());
1.1579 + // receiver type of mh is too wide; narrow to caller
1.1580 + if (!method.getDeclaringClass().isAssignableFrom(caller)) {
1.1581 + throw method.makeAccessException("caller class must be a subclass below the method", caller);
1.1582 + }
1.1583 + MethodType rawType = mh.type();
1.1584 + if (rawType.parameterType(0) == caller) return mh;
1.1585 + MethodType narrowType = rawType.changeParameterType(0, caller);
1.1586 + return mh.viewAsType(narrowType);
1.1587 + }
1.1588 +
1.1589 + /** Check access and get the requested method. */
1.1590 + private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1.1591 + final boolean doRestrict = true;
1.1592 + final boolean checkSecurity = true;
1.1593 + return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1.1594 + }
1.1595 + /** Check access and get the requested method, eliding receiver narrowing rules. */
1.1596 + private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1.1597 + final boolean doRestrict = false;
1.1598 + final boolean checkSecurity = true;
1.1599 + return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1.1600 + }
1.1601 + /** Check access and get the requested method, eliding security manager checks. */
1.1602 + private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1.1603 + final boolean doRestrict = true;
1.1604 + final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants
1.1605 + return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1.1606 + }
1.1607 + /** Common code for all methods; do not call directly except from immediately above. */
1.1608 + private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
1.1609 + boolean checkSecurity,
1.1610 + boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
1.1611 + checkMethod(refKind, refc, method);
1.1612 + // Optionally check with the security manager; this isn't needed for unreflect* calls.
1.1613 + if (checkSecurity)
1.1614 + checkSecurityManager(refc, method);
1.1615 + assert(!method.isMethodHandleInvoke());
1.1616 +
1.1617 + Class<?> refcAsSuper;
1.1618 + if (refKind == REF_invokeSpecial &&
1.1619 + refc != lookupClass() &&
1.1620 + !refc.isInterface() &&
1.1621 + refc != (refcAsSuper = lookupClass().getSuperclass()) &&
1.1622 + refc.isAssignableFrom(lookupClass())) {
1.1623 + assert(!method.getName().equals("<init>")); // not this code path
1.1624 + // Per JVMS 6.5, desc. of invokespecial instruction:
1.1625 + // If the method is in a superclass of the LC,
1.1626 + // and if our original search was above LC.super,
1.1627 + // repeat the search (symbolic lookup) from LC.super.
1.1628 + // FIXME: MemberName.resolve should handle this instead.
1.1629 + MemberName m2 = new MemberName(refcAsSuper,
1.1630 + method.getName(),
1.1631 + method.getMethodType(),
1.1632 + REF_invokeSpecial);
1.1633 + m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
1.1634 + if (m2 == null) throw new InternalError(method.toString());
1.1635 + method = m2;
1.1636 + refc = refcAsSuper;
1.1637 + // redo basic checks
1.1638 + checkMethod(refKind, refc, method);
1.1639 + }
1.1640 +
1.1641 + MethodHandle mh = DirectMethodHandle.make(refKind, refc, method);
1.1642 + mh = maybeBindCaller(method, mh, callerClass);
1.1643 + mh = mh.setVarargs(method);
1.1644 + // Optionally narrow the receiver argument to refc using restrictReceiver.
1.1645 + if (doRestrict &&
1.1646 + (refKind == REF_invokeSpecial ||
1.1647 + (MethodHandleNatives.refKindHasReceiver(refKind) &&
1.1648 + restrictProtectedReceiver(method))))
1.1649 + mh = restrictReceiver(method, mh, lookupClass());
1.1650 + return mh;
1.1651 + }
1.1652 + private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
1.1653 + Class<?> callerClass)
1.1654 + throws IllegalAccessException {
1.1655 + if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
1.1656 + return mh;
1.1657 + Class<?> hostClass = lookupClass;
1.1658 + if (!hasPrivateAccess()) // caller must have private access
1.1659 + hostClass = callerClass; // callerClass came from a security manager style stack walk
1.1660 + MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
1.1661 + // Note: caller will apply varargs after this step happens.
1.1662 + return cbmh;
1.1663 + }
1.1664 + /** Check access and get the requested field. */
1.1665 + private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
1.1666 + final boolean checkSecurity = true;
1.1667 + return getDirectFieldCommon(refKind, refc, field, checkSecurity);
1.1668 + }
1.1669 + /** Check access and get the requested field, eliding security manager checks. */
1.1670 + private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
1.1671 + final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants
1.1672 + return getDirectFieldCommon(refKind, refc, field, checkSecurity);
1.1673 + }
1.1674 + /** Common code for all fields; do not call directly except from immediately above. */
1.1675 + private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
1.1676 + boolean checkSecurity) throws IllegalAccessException {
1.1677 + checkField(refKind, refc, field);
1.1678 + // Optionally check with the security manager; this isn't needed for unreflect* calls.
1.1679 + if (checkSecurity)
1.1680 + checkSecurityManager(refc, field);
1.1681 + MethodHandle mh = DirectMethodHandle.make(refc, field);
1.1682 + boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
1.1683 + restrictProtectedReceiver(field));
1.1684 + if (doRestrict)
1.1685 + mh = restrictReceiver(field, mh, lookupClass());
1.1686 + return mh;
1.1687 + }
1.1688 + /** Check access and get the requested constructor. */
1.1689 + private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
1.1690 + final boolean checkSecurity = true;
1.1691 + return getDirectConstructorCommon(refc, ctor, checkSecurity);
1.1692 + }
1.1693 + /** Check access and get the requested constructor, eliding security manager checks. */
1.1694 + private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
1.1695 + final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants
1.1696 + return getDirectConstructorCommon(refc, ctor, checkSecurity);
1.1697 + }
1.1698 + /** Common code for all constructors; do not call directly except from immediately above. */
1.1699 + private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
1.1700 + boolean checkSecurity) throws IllegalAccessException {
1.1701 + assert(ctor.isConstructor());
1.1702 + checkAccess(REF_newInvokeSpecial, refc, ctor);
1.1703 + // Optionally check with the security manager; this isn't needed for unreflect* calls.
1.1704 + if (checkSecurity)
1.1705 + checkSecurityManager(refc, ctor);
1.1706 + assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here
1.1707 + return DirectMethodHandle.make(ctor).setVarargs(ctor);
1.1708 + }
1.1709 +
1.1710 + /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
1.1711 + */
1.1712 + /*non-public*/
1.1713 + MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
1.1714 + if (!(type instanceof Class || type instanceof MethodType))
1.1715 + throw new InternalError("unresolved MemberName");
1.1716 + MemberName member = new MemberName(refKind, defc, name, type);
1.1717 + MethodHandle mh = LOOKASIDE_TABLE.get(member);
1.1718 + if (mh != null) {
1.1719 + checkSymbolicClass(defc);
1.1720 + return mh;
1.1721 + }
1.1722 + // Treat MethodHandle.invoke and invokeExact specially.
1.1723 + if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
1.1724 + mh = findVirtualForMH(member.getName(), member.getMethodType());
1.1725 + if (mh != null) {
1.1726 + return mh;
1.1727 + }
1.1728 + }
1.1729 + MemberName resolved = resolveOrFail(refKind, member);
1.1730 + mh = getDirectMethodForConstant(refKind, defc, resolved);
1.1731 + if (mh instanceof DirectMethodHandle
1.1732 + && canBeCached(refKind, defc, resolved)) {
1.1733 + MemberName key = mh.internalMemberName();
1.1734 + if (key != null) {
1.1735 + key = key.asNormalOriginal();
1.1736 + }
1.1737 + if (member.equals(key)) { // better safe than sorry
1.1738 + LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
1.1739 + }
1.1740 + }
1.1741 + return mh;
1.1742 + }
1.1743 + private
1.1744 + boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
1.1745 + if (refKind == REF_invokeSpecial) {
1.1746 + return false;
1.1747 + }
1.1748 + if (!Modifier.isPublic(defc.getModifiers()) ||
1.1749 + !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
1.1750 + !member.isPublic() ||
1.1751 + member.isCallerSensitive()) {
1.1752 + return false;
1.1753 + }
1.1754 + ClassLoader loader = defc.getClassLoader();
1.1755 + if (!sun.misc.VM.isSystemDomainLoader(loader)) {
1.1756 + ClassLoader sysl = ClassLoader.getSystemClassLoader();
1.1757 + boolean found = false;
1.1758 + while (sysl != null) {
1.1759 + if (loader == sysl) { found = true; break; }
1.1760 + sysl = sysl.getParent();
1.1761 + }
1.1762 + if (!found) {
1.1763 + return false;
1.1764 + }
1.1765 + }
1.1766 + try {
1.1767 + MemberName resolved2 = publicLookup().resolveOrFail(refKind,
1.1768 + new MemberName(refKind, defc, member.getName(), member.getType()));
1.1769 + checkSecurityManager(defc, resolved2);
1.1770 + } catch (ReflectiveOperationException | SecurityException ex) {
1.1771 + return false;
1.1772 + }
1.1773 + return true;
1.1774 + }
1.1775 + private
1.1776 + MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
1.1777 + throws ReflectiveOperationException {
1.1778 + if (MethodHandleNatives.refKindIsField(refKind)) {
1.1779 + return getDirectFieldNoSecurityManager(refKind, defc, member);
1.1780 + } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
1.1781 + return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
1.1782 + } else if (refKind == REF_newInvokeSpecial) {
1.1783 + return getDirectConstructorNoSecurityManager(defc, member);
1.1784 + }
1.1785 + // oops
1.1786 + throw newIllegalArgumentException("bad MethodHandle constant #"+member);
1.1787 + }
1.1788 +
1.1789 + static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
1.1790 + }
1.1791 +
1.1792 + /**
1.1793 + * Produces a method handle giving read access to elements of an array.
1.1794 + * The type of the method handle will have a return type of the array's
1.1795 + * element type. Its first argument will be the array type,
1.1796 + * and the second will be {@code int}.
1.1797 + * @param arrayClass an array type
1.1798 + * @return a method handle which can load values from the given array type
1.1799 + * @throws NullPointerException if the argument is null
1.1800 + * @throws IllegalArgumentException if arrayClass is not an array type
1.1801 + */
1.1802 + public static
1.1803 + MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
1.1804 + return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
1.1805 + }
1.1806 +
1.1807 + /**
1.1808 + * Produces a method handle giving write access to elements of an array.
1.1809 + * The type of the method handle will have a void return type.
1.1810 + * Its last argument will be the array's element type.
1.1811 + * The first and second arguments will be the array type and int.
1.1812 + * @param arrayClass the class of an array
1.1813 + * @return a method handle which can store values into the array type
1.1814 + * @throws NullPointerException if the argument is null
1.1815 + * @throws IllegalArgumentException if arrayClass is not an array type
1.1816 + */
1.1817 + public static
1.1818 + MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
1.1819 + return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
1.1820 + }
1.1821 +
1.1822 + /// method handle invocation (reflective style)
1.1823 +
1.1824 + /**
1.1825 + * Produces a method handle which will invoke any method handle of the
1.1826 + * given {@code type}, with a given number of trailing arguments replaced by
1.1827 + * a single trailing {@code Object[]} array.
1.1828 + * The resulting invoker will be a method handle with the following
1.1829 + * arguments:
1.1830 + * <ul>
1.1831 + * <li>a single {@code MethodHandle} target
1.1832 + * <li>zero or more leading values (counted by {@code leadingArgCount})
1.1833 + * <li>an {@code Object[]} array containing trailing arguments
1.1834 + * </ul>
1.1835 + * <p>
1.1836 + * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
1.1837 + * the indicated {@code type}.
1.1838 + * That is, if the target is exactly of the given {@code type}, it will behave
1.1839 + * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
1.1840 + * is used to convert the target to the required {@code type}.
1.1841 + * <p>
1.1842 + * The type of the returned invoker will not be the given {@code type}, but rather
1.1843 + * will have all parameters except the first {@code leadingArgCount}
1.1844 + * replaced by a single array of type {@code Object[]}, which will be
1.1845 + * the final parameter.
1.1846 + * <p>
1.1847 + * Before invoking its target, the invoker will spread the final array, apply
1.1848 + * reference casts as necessary, and unbox and widen primitive arguments.
1.1849 + * If, when the invoker is called, the supplied array argument does
1.1850 + * not have the correct number of elements, the invoker will throw
1.1851 + * an {@link IllegalArgumentException} instead of invoking the target.
1.1852 + * <p>
1.1853 + * This method is equivalent to the following code (though it may be more efficient):
1.1854 + * <blockquote><pre>{@code
1.1855 +MethodHandle invoker = MethodHandles.invoker(type);
1.1856 +int spreadArgCount = type.parameterCount() - leadingArgCount;
1.1857 +invoker = invoker.asSpreader(Object[].class, spreadArgCount);
1.1858 +return invoker;
1.1859 + * }</pre></blockquote>
1.1860 + * This method throws no reflective or security exceptions.
1.1861 + * @param type the desired target type
1.1862 + * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
1.1863 + * @return a method handle suitable for invoking any method handle of the given type
1.1864 + * @throws NullPointerException if {@code type} is null
1.1865 + * @throws IllegalArgumentException if {@code leadingArgCount} is not in
1.1866 + * the range from 0 to {@code type.parameterCount()} inclusive,
1.1867 + * or if the resulting method handle's type would have
1.1868 + * <a href="MethodHandle.html#maxarity">too many parameters</a>
1.1869 + */
1.1870 + static public
1.1871 + MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
1.1872 + if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
1.1873 + throw new IllegalArgumentException("bad argument count "+leadingArgCount);
1.1874 + return type.invokers().spreadInvoker(leadingArgCount);
1.1875 + }
1.1876 +
1.1877 + /**
1.1878 + * Produces a special <em>invoker method handle</em> which can be used to
1.1879 + * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
1.1880 + * The resulting invoker will have a type which is
1.1881 + * exactly equal to the desired type, except that it will accept
1.1882 + * an additional leading argument of type {@code MethodHandle}.
1.1883 + * <p>
1.1884 + * This method is equivalent to the following code (though it may be more efficient):
1.1885 + * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
1.1886 + *
1.1887 + * <p style="font-size:smaller;">
1.1888 + * <em>Discussion:</em>
1.1889 + * Invoker method handles can be useful when working with variable method handles
1.1890 + * of unknown types.
1.1891 + * For example, to emulate an {@code invokeExact} call to a variable method
1.1892 + * handle {@code M}, extract its type {@code T},
1.1893 + * look up the invoker method {@code X} for {@code T},
1.1894 + * and call the invoker method, as {@code X.invoke(T, A...)}.
1.1895 + * (It would not work to call {@code X.invokeExact}, since the type {@code T}
1.1896 + * is unknown.)
1.1897 + * If spreading, collecting, or other argument transformations are required,
1.1898 + * they can be applied once to the invoker {@code X} and reused on many {@code M}
1.1899 + * method handle values, as long as they are compatible with the type of {@code X}.
1.1900 + * <p style="font-size:smaller;">
1.1901 + * <em>(Note: The invoker method is not available via the Core Reflection API.
1.1902 + * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
1.1903 + * on the declared {@code invokeExact} or {@code invoke} method will raise an
1.1904 + * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
1.1905 + * <p>
1.1906 + * This method throws no reflective or security exceptions.
1.1907 + * @param type the desired target type
1.1908 + * @return a method handle suitable for invoking any method handle of the given type
1.1909 + * @throws IllegalArgumentException if the resulting method handle's type would have
1.1910 + * <a href="MethodHandle.html#maxarity">too many parameters</a>
1.1911 + */
1.1912 + static public
1.1913 + MethodHandle exactInvoker(MethodType type) {
1.1914 + return type.invokers().exactInvoker();
1.1915 + }
1.1916 +
1.1917 + /**
1.1918 + * Produces a special <em>invoker method handle</em> which can be used to
1.1919 + * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
1.1920 + * The resulting invoker will have a type which is
1.1921 + * exactly equal to the desired type, except that it will accept
1.1922 + * an additional leading argument of type {@code MethodHandle}.
1.1923 + * <p>
1.1924 + * Before invoking its target, if the target differs from the expected type,
1.1925 + * the invoker will apply reference casts as
1.1926 + * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
1.1927 + * Similarly, the return value will be converted as necessary.
1.1928 + * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
1.1929 + * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
1.1930 + * <p>
1.1931 + * This method is equivalent to the following code (though it may be more efficient):
1.1932 + * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
1.1933 + * <p style="font-size:smaller;">
1.1934 + * <em>Discussion:</em>
1.1935 + * A {@linkplain MethodType#genericMethodType general method type} is one which
1.1936 + * mentions only {@code Object} arguments and return values.
1.1937 + * An invoker for such a type is capable of calling any method handle
1.1938 + * of the same arity as the general type.
1.1939 + * <p style="font-size:smaller;">
1.1940 + * <em>(Note: The invoker method is not available via the Core Reflection API.
1.1941 + * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
1.1942 + * on the declared {@code invokeExact} or {@code invoke} method will raise an
1.1943 + * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
1.1944 + * <p>
1.1945 + * This method throws no reflective or security exceptions.
1.1946 + * @param type the desired target type
1.1947 + * @return a method handle suitable for invoking any method handle convertible to the given type
1.1948 + * @throws IllegalArgumentException if the resulting method handle's type would have
1.1949 + * <a href="MethodHandle.html#maxarity">too many parameters</a>
1.1950 + */
1.1951 + static public
1.1952 + MethodHandle invoker(MethodType type) {
1.1953 + return type.invokers().generalInvoker();
1.1954 + }
1.1955 +
1.1956 + static /*non-public*/
1.1957 + MethodHandle basicInvoker(MethodType type) {
1.1958 + return type.form().basicInvoker();
1.1959 + }
1.1960 +
1.1961 + /// method handle modification (creation from other method handles)
1.1962 +
1.1963 + /**
1.1964 + * Produces a method handle which adapts the type of the
1.1965 + * given method handle to a new type by pairwise argument and return type conversion.
1.1966 + * The original type and new type must have the same number of arguments.
1.1967 + * The resulting method handle is guaranteed to report a type
1.1968 + * which is equal to the desired new type.
1.1969 + * <p>
1.1970 + * If the original type and new type are equal, returns target.
1.1971 + * <p>
1.1972 + * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
1.1973 + * and some additional conversions are also applied if those conversions fail.
1.1974 + * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
1.1975 + * if possible, before or instead of any conversions done by {@code asType}:
1.1976 + * <ul>
1.1977 + * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
1.1978 + * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
1.1979 + * (This treatment of interfaces follows the usage of the bytecode verifier.)
1.1980 + * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
1.1981 + * the boolean is converted to a byte value, 1 for true, 0 for false.
1.1982 + * (This treatment follows the usage of the bytecode verifier.)
1.1983 + * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
1.1984 + * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
1.1985 + * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
1.1986 + * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
1.1987 + * then a Java casting conversion (JLS 5.5) is applied.
1.1988 + * (Specifically, <em>T0</em> will convert to <em>T1</em> by
1.1989 + * widening and/or narrowing.)
1.1990 + * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
1.1991 + * conversion will be applied at runtime, possibly followed
1.1992 + * by a Java casting conversion (JLS 5.5) on the primitive value,
1.1993 + * possibly followed by a conversion from byte to boolean by testing
1.1994 + * the low-order bit.
1.1995 + * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
1.1996 + * and if the reference is null at runtime, a zero value is introduced.
1.1997 + * </ul>
1.1998 + * @param target the method handle to invoke after arguments are retyped
1.1999 + * @param newType the expected type of the new method handle
1.2000 + * @return a method handle which delegates to the target after performing
1.2001 + * any necessary argument conversions, and arranges for any
1.2002 + * necessary return value conversions
1.2003 + * @throws NullPointerException if either argument is null
1.2004 + * @throws WrongMethodTypeException if the conversion cannot be made
1.2005 + * @see MethodHandle#asType
1.2006 + */
1.2007 + public static
1.2008 + MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
1.2009 + if (!target.type().isCastableTo(newType)) {
1.2010 + throw new WrongMethodTypeException("cannot explicitly cast "+target+" to "+newType);
1.2011 + }
1.2012 + return MethodHandleImpl.makePairwiseConvert(target, newType, 2);
1.2013 + }
1.2014 +
1.2015 + /**
1.2016 + * Produces a method handle which adapts the calling sequence of the
1.2017 + * given method handle to a new type, by reordering the arguments.
1.2018 + * The resulting method handle is guaranteed to report a type
1.2019 + * which is equal to the desired new type.
1.2020 + * <p>
1.2021 + * The given array controls the reordering.
1.2022 + * Call {@code #I} the number of incoming parameters (the value
1.2023 + * {@code newType.parameterCount()}, and call {@code #O} the number
1.2024 + * of outgoing parameters (the value {@code target.type().parameterCount()}).
1.2025 + * Then the length of the reordering array must be {@code #O},
1.2026 + * and each element must be a non-negative number less than {@code #I}.
1.2027 + * For every {@code N} less than {@code #O}, the {@code N}-th
1.2028 + * outgoing argument will be taken from the {@code I}-th incoming
1.2029 + * argument, where {@code I} is {@code reorder[N]}.
1.2030 + * <p>
1.2031 + * No argument or return value conversions are applied.
1.2032 + * The type of each incoming argument, as determined by {@code newType},
1.2033 + * must be identical to the type of the corresponding outgoing parameter
1.2034 + * or parameters in the target method handle.
1.2035 + * The return type of {@code newType} must be identical to the return
1.2036 + * type of the original target.
1.2037 + * <p>
1.2038 + * The reordering array need not specify an actual permutation.
1.2039 + * An incoming argument will be duplicated if its index appears
1.2040 + * more than once in the array, and an incoming argument will be dropped
1.2041 + * if its index does not appear in the array.
1.2042 + * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
1.2043 + * incoming arguments which are not mentioned in the reordering array
1.2044 + * are may be any type, as determined only by {@code newType}.
1.2045 + * <blockquote><pre>{@code
1.2046 +import static java.lang.invoke.MethodHandles.*;
1.2047 +import static java.lang.invoke.MethodType.*;
1.2048 +...
1.2049 +MethodType intfn1 = methodType(int.class, int.class);
1.2050 +MethodType intfn2 = methodType(int.class, int.class, int.class);
1.2051 +MethodHandle sub = ... (int x, int y) -> (x-y) ...;
1.2052 +assert(sub.type().equals(intfn2));
1.2053 +MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
1.2054 +MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
1.2055 +assert((int)rsub.invokeExact(1, 100) == 99);
1.2056 +MethodHandle add = ... (int x, int y) -> (x+y) ...;
1.2057 +assert(add.type().equals(intfn2));
1.2058 +MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
1.2059 +assert(twice.type().equals(intfn1));
1.2060 +assert((int)twice.invokeExact(21) == 42);
1.2061 + * }</pre></blockquote>
1.2062 + * @param target the method handle to invoke after arguments are reordered
1.2063 + * @param newType the expected type of the new method handle
1.2064 + * @param reorder an index array which controls the reordering
1.2065 + * @return a method handle which delegates to the target after it
1.2066 + * drops unused arguments and moves and/or duplicates the other arguments
1.2067 + * @throws NullPointerException if any argument is null
1.2068 + * @throws IllegalArgumentException if the index array length is not equal to
1.2069 + * the arity of the target, or if any index array element
1.2070 + * not a valid index for a parameter of {@code newType},
1.2071 + * or if two corresponding parameter types in
1.2072 + * {@code target.type()} and {@code newType} are not identical,
1.2073 + */
1.2074 + public static
1.2075 + MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
1.2076 + checkReorder(reorder, newType, target.type());
1.2077 + return target.permuteArguments(newType, reorder);
1.2078 + }
1.2079 +
1.2080 + private static void checkReorder(int[] reorder, MethodType newType, MethodType oldType) {
1.2081 + if (newType.returnType() != oldType.returnType())
1.2082 + throw newIllegalArgumentException("return types do not match",
1.2083 + oldType, newType);
1.2084 + if (reorder.length == oldType.parameterCount()) {
1.2085 + int limit = newType.parameterCount();
1.2086 + boolean bad = false;
1.2087 + for (int j = 0; j < reorder.length; j++) {
1.2088 + int i = reorder[j];
1.2089 + if (i < 0 || i >= limit) {
1.2090 + bad = true; break;
1.2091 + }
1.2092 + Class<?> src = newType.parameterType(i);
1.2093 + Class<?> dst = oldType.parameterType(j);
1.2094 + if (src != dst)
1.2095 + throw newIllegalArgumentException("parameter types do not match after reorder",
1.2096 + oldType, newType);
1.2097 + }
1.2098 + if (!bad) return;
1.2099 + }
1.2100 + throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
1.2101 + }
1.2102 +
1.2103 + /**
1.2104 + * Produces a method handle of the requested return type which returns the given
1.2105 + * constant value every time it is invoked.
1.2106 + * <p>
1.2107 + * Before the method handle is returned, the passed-in value is converted to the requested type.
1.2108 + * If the requested type is primitive, widening primitive conversions are attempted,
1.2109 + * else reference conversions are attempted.
1.2110 + * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
1.2111 + * @param type the return type of the desired method handle
1.2112 + * @param value the value to return
1.2113 + * @return a method handle of the given return type and no arguments, which always returns the given value
1.2114 + * @throws NullPointerException if the {@code type} argument is null
1.2115 + * @throws ClassCastException if the value cannot be converted to the required return type
1.2116 + * @throws IllegalArgumentException if the given type is {@code void.class}
1.2117 + */
1.2118 + public static
1.2119 + MethodHandle constant(Class<?> type, Object value) {
1.2120 + if (type.isPrimitive()) {
1.2121 + if (type == void.class)
1.2122 + throw newIllegalArgumentException("void type");
1.2123 + Wrapper w = Wrapper.forPrimitiveType(type);
1.2124 + return insertArguments(identity(type), 0, w.convert(value, type));
1.2125 + } else {
1.2126 + return identity(type).bindTo(type.cast(value));
1.2127 + }
1.2128 + }
1.2129 +
1.2130 + /**
1.2131 + * Produces a method handle which returns its sole argument when invoked.
1.2132 + * @param type the type of the sole parameter and return value of the desired method handle
1.2133 + * @return a unary method handle which accepts and returns the given type
1.2134 + * @throws NullPointerException if the argument is null
1.2135 + * @throws IllegalArgumentException if the given type is {@code void.class}
1.2136 + */
1.2137 + public static
1.2138 + MethodHandle identity(Class<?> type) {
1.2139 + if (type == void.class)
1.2140 + throw newIllegalArgumentException("void type");
1.2141 + else if (type == Object.class)
1.2142 + return ValueConversions.identity();
1.2143 + else if (type.isPrimitive())
1.2144 + return ValueConversions.identity(Wrapper.forPrimitiveType(type));
1.2145 + else
1.2146 + return MethodHandleImpl.makeReferenceIdentity(type);
1.2147 + }
1.2148 +
1.2149 + /**
1.2150 + * Provides a target method handle with one or more <em>bound arguments</em>
1.2151 + * in advance of the method handle's invocation.
1.2152 + * The formal parameters to the target corresponding to the bound
1.2153 + * arguments are called <em>bound parameters</em>.
1.2154 + * Returns a new method handle which saves away the bound arguments.
1.2155 + * When it is invoked, it receives arguments for any non-bound parameters,
1.2156 + * binds the saved arguments to their corresponding parameters,
1.2157 + * and calls the original target.
1.2158 + * <p>
1.2159 + * The type of the new method handle will drop the types for the bound
1.2160 + * parameters from the original target type, since the new method handle
1.2161 + * will no longer require those arguments to be supplied by its callers.
1.2162 + * <p>
1.2163 + * Each given argument object must match the corresponding bound parameter type.
1.2164 + * If a bound parameter type is a primitive, the argument object
1.2165 + * must be a wrapper, and will be unboxed to produce the primitive value.
1.2166 + * <p>
1.2167 + * The {@code pos} argument selects which parameters are to be bound.
1.2168 + * It may range between zero and <i>N-L</i> (inclusively),
1.2169 + * where <i>N</i> is the arity of the target method handle
1.2170 + * and <i>L</i> is the length of the values array.
1.2171 + * @param target the method handle to invoke after the argument is inserted
1.2172 + * @param pos where to insert the argument (zero for the first)
1.2173 + * @param values the series of arguments to insert
1.2174 + * @return a method handle which inserts an additional argument,
1.2175 + * before calling the original method handle
1.2176 + * @throws NullPointerException if the target or the {@code values} array is null
1.2177 + * @see MethodHandle#bindTo
1.2178 + */
1.2179 + public static
1.2180 + MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
1.2181 + int insCount = values.length;
1.2182 + MethodType oldType = target.type();
1.2183 + int outargs = oldType.parameterCount();
1.2184 + int inargs = outargs - insCount;
1.2185 + if (inargs < 0)
1.2186 + throw newIllegalArgumentException("too many values to insert");
1.2187 + if (pos < 0 || pos > inargs)
1.2188 + throw newIllegalArgumentException("no argument type to append");
1.2189 + MethodHandle result = target;
1.2190 + for (int i = 0; i < insCount; i++) {
1.2191 + Object value = values[i];
1.2192 + Class<?> ptype = oldType.parameterType(pos+i);
1.2193 + if (ptype.isPrimitive()) {
1.2194 + char btype = 'I';
1.2195 + Wrapper w = Wrapper.forPrimitiveType(ptype);
1.2196 + switch (w) {
1.2197 + case LONG: btype = 'J'; break;
1.2198 + case FLOAT: btype = 'F'; break;
1.2199 + case DOUBLE: btype = 'D'; break;
1.2200 + }
1.2201 + // perform unboxing and/or primitive conversion
1.2202 + value = w.convert(value, ptype);
1.2203 + result = result.bindArgument(pos, btype, value);
1.2204 + continue;
1.2205 + }
1.2206 + value = ptype.cast(value); // throw CCE if needed
1.2207 + if (pos == 0) {
1.2208 + result = result.bindReceiver(value);
1.2209 + } else {
1.2210 + result = result.bindArgument(pos, 'L', value);
1.2211 + }
1.2212 + }
1.2213 + return result;
1.2214 + }
1.2215 +
1.2216 + /**
1.2217 + * Produces a method handle which will discard some dummy arguments
1.2218 + * before calling some other specified <i>target</i> method handle.
1.2219 + * The type of the new method handle will be the same as the target's type,
1.2220 + * except it will also include the dummy argument types,
1.2221 + * at some given position.
1.2222 + * <p>
1.2223 + * The {@code pos} argument may range between zero and <i>N</i>,
1.2224 + * where <i>N</i> is the arity of the target.
1.2225 + * If {@code pos} is zero, the dummy arguments will precede
1.2226 + * the target's real arguments; if {@code pos} is <i>N</i>
1.2227 + * they will come after.
1.2228 + * <p>
1.2229 + * <b>Example:</b>
1.2230 + * <blockquote><pre>{@code
1.2231 +import static java.lang.invoke.MethodHandles.*;
1.2232 +import static java.lang.invoke.MethodType.*;
1.2233 +...
1.2234 +MethodHandle cat = lookup().findVirtual(String.class,
1.2235 + "concat", methodType(String.class, String.class));
1.2236 +assertEquals("xy", (String) cat.invokeExact("x", "y"));
1.2237 +MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
1.2238 +MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
1.2239 +assertEquals(bigType, d0.type());
1.2240 +assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
1.2241 + * }</pre></blockquote>
1.2242 + * <p>
1.2243 + * This method is also equivalent to the following code:
1.2244 + * <blockquote><pre>
1.2245 + * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
1.2246 + * </pre></blockquote>
1.2247 + * @param target the method handle to invoke after the arguments are dropped
1.2248 + * @param valueTypes the type(s) of the argument(s) to drop
1.2249 + * @param pos position of first argument to drop (zero for the leftmost)
1.2250 + * @return a method handle which drops arguments of the given types,
1.2251 + * before calling the original method handle
1.2252 + * @throws NullPointerException if the target is null,
1.2253 + * or if the {@code valueTypes} list or any of its elements is null
1.2254 + * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
1.2255 + * or if {@code pos} is negative or greater than the arity of the target,
1.2256 + * or if the new method handle's type would have too many parameters
1.2257 + */
1.2258 + public static
1.2259 + MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
1.2260 + MethodType oldType = target.type(); // get NPE
1.2261 + int dropped = valueTypes.size();
1.2262 + MethodType.checkSlotCount(dropped);
1.2263 + if (dropped == 0) return target;
1.2264 + int outargs = oldType.parameterCount();
1.2265 + int inargs = outargs + dropped;
1.2266 + if (pos < 0 || pos >= inargs)
1.2267 + throw newIllegalArgumentException("no argument type to remove");
1.2268 + ArrayList<Class<?>> ptypes = new ArrayList<>(oldType.parameterList());
1.2269 + ptypes.addAll(pos, valueTypes);
1.2270 + MethodType newType = MethodType.methodType(oldType.returnType(), ptypes);
1.2271 + return target.dropArguments(newType, pos, dropped);
1.2272 + }
1.2273 +
1.2274 + /**
1.2275 + * Produces a method handle which will discard some dummy arguments
1.2276 + * before calling some other specified <i>target</i> method handle.
1.2277 + * The type of the new method handle will be the same as the target's type,
1.2278 + * except it will also include the dummy argument types,
1.2279 + * at some given position.
1.2280 + * <p>
1.2281 + * The {@code pos} argument may range between zero and <i>N</i>,
1.2282 + * where <i>N</i> is the arity of the target.
1.2283 + * If {@code pos} is zero, the dummy arguments will precede
1.2284 + * the target's real arguments; if {@code pos} is <i>N</i>
1.2285 + * they will come after.
1.2286 + * <p>
1.2287 + * <b>Example:</b>
1.2288 + * <blockquote><pre>{@code
1.2289 +import static java.lang.invoke.MethodHandles.*;
1.2290 +import static java.lang.invoke.MethodType.*;
1.2291 +...
1.2292 +MethodHandle cat = lookup().findVirtual(String.class,
1.2293 + "concat", methodType(String.class, String.class));
1.2294 +assertEquals("xy", (String) cat.invokeExact("x", "y"));
1.2295 +MethodHandle d0 = dropArguments(cat, 0, String.class);
1.2296 +assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
1.2297 +MethodHandle d1 = dropArguments(cat, 1, String.class);
1.2298 +assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
1.2299 +MethodHandle d2 = dropArguments(cat, 2, String.class);
1.2300 +assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
1.2301 +MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
1.2302 +assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
1.2303 + * }</pre></blockquote>
1.2304 + * <p>
1.2305 + * This method is also equivalent to the following code:
1.2306 + * <blockquote><pre>
1.2307 + * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
1.2308 + * </pre></blockquote>
1.2309 + * @param target the method handle to invoke after the arguments are dropped
1.2310 + * @param valueTypes the type(s) of the argument(s) to drop
1.2311 + * @param pos position of first argument to drop (zero for the leftmost)
1.2312 + * @return a method handle which drops arguments of the given types,
1.2313 + * before calling the original method handle
1.2314 + * @throws NullPointerException if the target is null,
1.2315 + * or if the {@code valueTypes} array or any of its elements is null
1.2316 + * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
1.2317 + * or if {@code pos} is negative or greater than the arity of the target,
1.2318 + * or if the new method handle's type would have
1.2319 + * <a href="MethodHandle.html#maxarity">too many parameters</a>
1.2320 + */
1.2321 + public static
1.2322 + MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
1.2323 + return dropArguments(target, pos, Arrays.asList(valueTypes));
1.2324 + }
1.2325 +
1.2326 + /**
1.2327 + * Adapts a target method handle by pre-processing
1.2328 + * one or more of its arguments, each with its own unary filter function,
1.2329 + * and then calling the target with each pre-processed argument
1.2330 + * replaced by the result of its corresponding filter function.
1.2331 + * <p>
1.2332 + * The pre-processing is performed by one or more method handles,
1.2333 + * specified in the elements of the {@code filters} array.
1.2334 + * The first element of the filter array corresponds to the {@code pos}
1.2335 + * argument of the target, and so on in sequence.
1.2336 + * <p>
1.2337 + * Null arguments in the array are treated as identity functions,
1.2338 + * and the corresponding arguments left unchanged.
1.2339 + * (If there are no non-null elements in the array, the original target is returned.)
1.2340 + * Each filter is applied to the corresponding argument of the adapter.
1.2341 + * <p>
1.2342 + * If a filter {@code F} applies to the {@code N}th argument of
1.2343 + * the target, then {@code F} must be a method handle which
1.2344 + * takes exactly one argument. The type of {@code F}'s sole argument
1.2345 + * replaces the corresponding argument type of the target
1.2346 + * in the resulting adapted method handle.
1.2347 + * The return type of {@code F} must be identical to the corresponding
1.2348 + * parameter type of the target.
1.2349 + * <p>
1.2350 + * It is an error if there are elements of {@code filters}
1.2351 + * (null or not)
1.2352 + * which do not correspond to argument positions in the target.
1.2353 + * <p><b>Example:</b>
1.2354 + * <blockquote><pre>{@code
1.2355 +import static java.lang.invoke.MethodHandles.*;
1.2356 +import static java.lang.invoke.MethodType.*;
1.2357 +...
1.2358 +MethodHandle cat = lookup().findVirtual(String.class,
1.2359 + "concat", methodType(String.class, String.class));
1.2360 +MethodHandle upcase = lookup().findVirtual(String.class,
1.2361 + "toUpperCase", methodType(String.class));
1.2362 +assertEquals("xy", (String) cat.invokeExact("x", "y"));
1.2363 +MethodHandle f0 = filterArguments(cat, 0, upcase);
1.2364 +assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
1.2365 +MethodHandle f1 = filterArguments(cat, 1, upcase);
1.2366 +assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
1.2367 +MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
1.2368 +assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
1.2369 + * }</pre></blockquote>
1.2370 + * <p> Here is pseudocode for the resulting adapter:
1.2371 + * <blockquote><pre>{@code
1.2372 + * V target(P... p, A[i]... a[i], B... b);
1.2373 + * A[i] filter[i](V[i]);
1.2374 + * T adapter(P... p, V[i]... v[i], B... b) {
1.2375 + * return target(p..., f[i](v[i])..., b...);
1.2376 + * }
1.2377 + * }</pre></blockquote>
1.2378 + *
1.2379 + * @param target the method handle to invoke after arguments are filtered
1.2380 + * @param pos the position of the first argument to filter
1.2381 + * @param filters method handles to call initially on filtered arguments
1.2382 + * @return method handle which incorporates the specified argument filtering logic
1.2383 + * @throws NullPointerException if the target is null
1.2384 + * or if the {@code filters} array is null
1.2385 + * @throws IllegalArgumentException if a non-null element of {@code filters}
1.2386 + * does not match a corresponding argument type of target as described above,
1.2387 + * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
1.2388 + * or if the resulting method handle's type would have
1.2389 + * <a href="MethodHandle.html#maxarity">too many parameters</a>
1.2390 + */
1.2391 + public static
1.2392 + MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
1.2393 + MethodType targetType = target.type();
1.2394 + MethodHandle adapter = target;
1.2395 + MethodType adapterType = null;
1.2396 + assert((adapterType = targetType) != null);
1.2397 + int maxPos = targetType.parameterCount();
1.2398 + if (pos + filters.length > maxPos)
1.2399 + throw newIllegalArgumentException("too many filters");
1.2400 + int curPos = pos-1; // pre-incremented
1.2401 + for (MethodHandle filter : filters) {
1.2402 + curPos += 1;
1.2403 + if (filter == null) continue; // ignore null elements of filters
1.2404 + adapter = filterArgument(adapter, curPos, filter);
1.2405 + assert((adapterType = adapterType.changeParameterType(curPos, filter.type().parameterType(0))) != null);
1.2406 + }
1.2407 + assert(adapterType.equals(adapter.type()));
1.2408 + return adapter;
1.2409 + }
1.2410 +
1.2411 + /*non-public*/ static
1.2412 + MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
1.2413 + MethodType targetType = target.type();
1.2414 + MethodType filterType = filter.type();
1.2415 + if (filterType.parameterCount() != 1
1.2416 + || filterType.returnType() != targetType.parameterType(pos))
1.2417 + throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
1.2418 + return MethodHandleImpl.makeCollectArguments(target, filter, pos, false);
1.2419 + }
1.2420 +
1.2421 + /**
1.2422 + * Adapts a target method handle by pre-processing
1.2423 + * a sub-sequence of its arguments with a filter (another method handle).
1.2424 + * The pre-processed arguments are replaced by the result (if any) of the
1.2425 + * filter function.
1.2426 + * The target is then called on the modified (usually shortened) argument list.
1.2427 + * <p>
1.2428 + * If the filter returns a value, the target must accept that value as
1.2429 + * its argument in position {@code pos}, preceded and/or followed by
1.2430 + * any arguments not passed to the filter.
1.2431 + * If the filter returns void, the target must accept all arguments
1.2432 + * not passed to the filter.
1.2433 + * No arguments are reordered, and a result returned from the filter
1.2434 + * replaces (in order) the whole subsequence of arguments originally
1.2435 + * passed to the adapter.
1.2436 + * <p>
1.2437 + * The argument types (if any) of the filter
1.2438 + * replace zero or one argument types of the target, at position {@code pos},
1.2439 + * in the resulting adapted method handle.
1.2440 + * The return type of the filter (if any) must be identical to the
1.2441 + * argument type of the target at position {@code pos}, and that target argument
1.2442 + * is supplied by the return value of the filter.
1.2443 + * <p>
1.2444 + * In all cases, {@code pos} must be greater than or equal to zero, and
1.2445 + * {@code pos} must also be less than or equal to the target's arity.
1.2446 + * <p><b>Example:</b>
1.2447 + * <blockquote><pre>{@code
1.2448 +import static java.lang.invoke.MethodHandles.*;
1.2449 +import static java.lang.invoke.MethodType.*;
1.2450 +...
1.2451 +MethodHandle deepToString = publicLookup()
1.2452 + .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
1.2453 +
1.2454 +MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
1.2455 +assertEquals("[strange]", (String) ts1.invokeExact("strange"));
1.2456 +
1.2457 +MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
1.2458 +assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
1.2459 +
1.2460 +MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
1.2461 +MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
1.2462 +assertEquals("[top, [up, down], strange]",
1.2463 + (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
1.2464 +
1.2465 +MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
1.2466 +assertEquals("[top, [up, down], [strange]]",
1.2467 + (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
1.2468 +
1.2469 +MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
1.2470 +assertEquals("[top, [[up, down, strange], charm], bottom]",
1.2471 + (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
1.2472 + * }</pre></blockquote>
1.2473 + * <p> Here is pseudocode for the resulting adapter:
1.2474 + * <blockquote><pre>{@code
1.2475 + * T target(A...,V,C...);
1.2476 + * V filter(B...);
1.2477 + * T adapter(A... a,B... b,C... c) {
1.2478 + * V v = filter(b...);
1.2479 + * return target(a...,v,c...);
1.2480 + * }
1.2481 + * // and if the filter has no arguments:
1.2482 + * T target2(A...,V,C...);
1.2483 + * V filter2();
1.2484 + * T adapter2(A... a,C... c) {
1.2485 + * V v = filter2();
1.2486 + * return target2(a...,v,c...);
1.2487 + * }
1.2488 + * // and if the filter has a void return:
1.2489 + * T target3(A...,C...);
1.2490 + * void filter3(B...);
1.2491 + * void adapter3(A... a,B... b,C... c) {
1.2492 + * filter3(b...);
1.2493 + * return target3(a...,c...);
1.2494 + * }
1.2495 + * }</pre></blockquote>
1.2496 + * <p>
1.2497 + * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
1.2498 + * one which first "folds" the affected arguments, and then drops them, in separate
1.2499 + * steps as follows:
1.2500 + * <blockquote><pre>{@code
1.2501 + * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
1.2502 + * mh = MethodHandles.foldArguments(mh, coll); //step 1
1.2503 + * }</pre></blockquote>
1.2504 + * If the target method handle consumes no arguments besides than the result
1.2505 + * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
1.2506 + * is equivalent to {@code filterReturnValue(coll, mh)}.
1.2507 + * If the filter method handle {@code coll} consumes one argument and produces
1.2508 + * a non-void result, then {@code collectArguments(mh, N, coll)}
1.2509 + * is equivalent to {@code filterArguments(mh, N, coll)}.
1.2510 + * Other equivalences are possible but would require argument permutation.
1.2511 + *
1.2512 + * @param target the method handle to invoke after filtering the subsequence of arguments
1.2513 + * @param pos the position of the first adapter argument to pass to the filter,
1.2514 + * and/or the target argument which receives the result of the filter
1.2515 + * @param filter method handle to call on the subsequence of arguments
1.2516 + * @return method handle which incorporates the specified argument subsequence filtering logic
1.2517 + * @throws NullPointerException if either argument is null
1.2518 + * @throws IllegalArgumentException if the return type of {@code filter}
1.2519 + * is non-void and is not the same as the {@code pos} argument of the target,
1.2520 + * or if {@code pos} is not between 0 and the target's arity, inclusive,
1.2521 + * or if the resulting method handle's type would have
1.2522 + * <a href="MethodHandle.html#maxarity">too many parameters</a>
1.2523 + * @see MethodHandles#foldArguments
1.2524 + * @see MethodHandles#filterArguments
1.2525 + * @see MethodHandles#filterReturnValue
1.2526 + */
1.2527 + public static
1.2528 + MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
1.2529 + MethodType targetType = target.type();
1.2530 + MethodType filterType = filter.type();
1.2531 + if (filterType.returnType() != void.class &&
1.2532 + filterType.returnType() != targetType.parameterType(pos))
1.2533 + throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
1.2534 + return MethodHandleImpl.makeCollectArguments(target, filter, pos, false);
1.2535 + }
1.2536 +
1.2537 + /**
1.2538 + * Adapts a target method handle by post-processing
1.2539 + * its return value (if any) with a filter (another method handle).
1.2540 + * The result of the filter is returned from the adapter.
1.2541 + * <p>
1.2542 + * If the target returns a value, the filter must accept that value as
1.2543 + * its only argument.
1.2544 + * If the target returns void, the filter must accept no arguments.
1.2545 + * <p>
1.2546 + * The return type of the filter
1.2547 + * replaces the return type of the target
1.2548 + * in the resulting adapted method handle.
1.2549 + * The argument type of the filter (if any) must be identical to the
1.2550 + * return type of the target.
1.2551 + * <p><b>Example:</b>
1.2552 + * <blockquote><pre>{@code
1.2553 +import static java.lang.invoke.MethodHandles.*;
1.2554 +import static java.lang.invoke.MethodType.*;
1.2555 +...
1.2556 +MethodHandle cat = lookup().findVirtual(String.class,
1.2557 + "concat", methodType(String.class, String.class));
1.2558 +MethodHandle length = lookup().findVirtual(String.class,
1.2559 + "length", methodType(int.class));
1.2560 +System.out.println((String) cat.invokeExact("x", "y")); // xy
1.2561 +MethodHandle f0 = filterReturnValue(cat, length);
1.2562 +System.out.println((int) f0.invokeExact("x", "y")); // 2
1.2563 + * }</pre></blockquote>
1.2564 + * <p> Here is pseudocode for the resulting adapter:
1.2565 + * <blockquote><pre>{@code
1.2566 + * V target(A...);
1.2567 + * T filter(V);
1.2568 + * T adapter(A... a) {
1.2569 + * V v = target(a...);
1.2570 + * return filter(v);
1.2571 + * }
1.2572 + * // and if the target has a void return:
1.2573 + * void target2(A...);
1.2574 + * T filter2();
1.2575 + * T adapter2(A... a) {
1.2576 + * target2(a...);
1.2577 + * return filter2();
1.2578 + * }
1.2579 + * // and if the filter has a void return:
1.2580 + * V target3(A...);
1.2581 + * void filter3(V);
1.2582 + * void adapter3(A... a) {
1.2583 + * V v = target3(a...);
1.2584 + * filter3(v);
1.2585 + * }
1.2586 + * }</pre></blockquote>
1.2587 + * @param target the method handle to invoke before filtering the return value
1.2588 + * @param filter method handle to call on the return value
1.2589 + * @return method handle which incorporates the specified return value filtering logic
1.2590 + * @throws NullPointerException if either argument is null
1.2591 + * @throws IllegalArgumentException if the argument list of {@code filter}
1.2592 + * does not match the return type of target as described above
1.2593 + */
1.2594 + public static
1.2595 + MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
1.2596 + MethodType targetType = target.type();
1.2597 + MethodType filterType = filter.type();
1.2598 + Class<?> rtype = targetType.returnType();
1.2599 + int filterValues = filterType.parameterCount();
1.2600 + if (filterValues == 0
1.2601 + ? (rtype != void.class)
1.2602 + : (rtype != filterType.parameterType(0)))
1.2603 + throw newIllegalArgumentException("target and filter types do not match", target, filter);
1.2604 + // result = fold( lambda(retval, arg...) { filter(retval) },
1.2605 + // lambda( arg...) { target(arg...) } )
1.2606 + return MethodHandleImpl.makeCollectArguments(filter, target, 0, false);
1.2607 + }
1.2608 +
1.2609 + /**
1.2610 + * Adapts a target method handle by pre-processing
1.2611 + * some of its arguments, and then calling the target with
1.2612 + * the result of the pre-processing, inserted into the original
1.2613 + * sequence of arguments.
1.2614 + * <p>
1.2615 + * The pre-processing is performed by {@code combiner}, a second method handle.
1.2616 + * Of the arguments passed to the adapter, the first {@code N} arguments
1.2617 + * are copied to the combiner, which is then called.
1.2618 + * (Here, {@code N} is defined as the parameter count of the combiner.)
1.2619 + * After this, control passes to the target, with any result
1.2620 + * from the combiner inserted before the original {@code N} incoming
1.2621 + * arguments.
1.2622 + * <p>
1.2623 + * If the combiner returns a value, the first parameter type of the target
1.2624 + * must be identical with the return type of the combiner, and the next
1.2625 + * {@code N} parameter types of the target must exactly match the parameters
1.2626 + * of the combiner.
1.2627 + * <p>
1.2628 + * If the combiner has a void return, no result will be inserted,
1.2629 + * and the first {@code N} parameter types of the target
1.2630 + * must exactly match the parameters of the combiner.
1.2631 + * <p>
1.2632 + * The resulting adapter is the same type as the target, except that the
1.2633 + * first parameter type is dropped,
1.2634 + * if it corresponds to the result of the combiner.
1.2635 + * <p>
1.2636 + * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
1.2637 + * that either the combiner or the target does not wish to receive.
1.2638 + * If some of the incoming arguments are destined only for the combiner,
1.2639 + * consider using {@link MethodHandle#asCollector asCollector} instead, since those
1.2640 + * arguments will not need to be live on the stack on entry to the
1.2641 + * target.)
1.2642 + * <p><b>Example:</b>
1.2643 + * <blockquote><pre>{@code
1.2644 +import static java.lang.invoke.MethodHandles.*;
1.2645 +import static java.lang.invoke.MethodType.*;
1.2646 +...
1.2647 +MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
1.2648 + "println", methodType(void.class, String.class))
1.2649 + .bindTo(System.out);
1.2650 +MethodHandle cat = lookup().findVirtual(String.class,
1.2651 + "concat", methodType(String.class, String.class));
1.2652 +assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
1.2653 +MethodHandle catTrace = foldArguments(cat, trace);
1.2654 +// also prints "boo":
1.2655 +assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
1.2656 + * }</pre></blockquote>
1.2657 + * <p> Here is pseudocode for the resulting adapter:
1.2658 + * <blockquote><pre>{@code
1.2659 + * // there are N arguments in A...
1.2660 + * T target(V, A[N]..., B...);
1.2661 + * V combiner(A...);
1.2662 + * T adapter(A... a, B... b) {
1.2663 + * V v = combiner(a...);
1.2664 + * return target(v, a..., b...);
1.2665 + * }
1.2666 + * // and if the combiner has a void return:
1.2667 + * T target2(A[N]..., B...);
1.2668 + * void combiner2(A...);
1.2669 + * T adapter2(A... a, B... b) {
1.2670 + * combiner2(a...);
1.2671 + * return target2(a..., b...);
1.2672 + * }
1.2673 + * }</pre></blockquote>
1.2674 + * @param target the method handle to invoke after arguments are combined
1.2675 + * @param combiner method handle to call initially on the incoming arguments
1.2676 + * @return method handle which incorporates the specified argument folding logic
1.2677 + * @throws NullPointerException if either argument is null
1.2678 + * @throws IllegalArgumentException if {@code combiner}'s return type
1.2679 + * is non-void and not the same as the first argument type of
1.2680 + * the target, or if the initial {@code N} argument types
1.2681 + * of the target
1.2682 + * (skipping one matching the {@code combiner}'s return type)
1.2683 + * are not identical with the argument types of {@code combiner}
1.2684 + */
1.2685 + public static
1.2686 + MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
1.2687 + int pos = 0;
1.2688 + MethodType targetType = target.type();
1.2689 + MethodType combinerType = combiner.type();
1.2690 + int foldPos = pos;
1.2691 + int foldArgs = combinerType.parameterCount();
1.2692 + int foldVals = combinerType.returnType() == void.class ? 0 : 1;
1.2693 + int afterInsertPos = foldPos + foldVals;
1.2694 + boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
1.2695 + if (ok && !(combinerType.parameterList()
1.2696 + .equals(targetType.parameterList().subList(afterInsertPos,
1.2697 + afterInsertPos + foldArgs))))
1.2698 + ok = false;
1.2699 + if (ok && foldVals != 0 && !combinerType.returnType().equals(targetType.parameterType(0)))
1.2700 + ok = false;
1.2701 + if (!ok)
1.2702 + throw misMatchedTypes("target and combiner types", targetType, combinerType);
1.2703 + MethodType newType = targetType.dropParameterTypes(foldPos, afterInsertPos);
1.2704 + return MethodHandleImpl.makeCollectArguments(target, combiner, foldPos, true);
1.2705 + }
1.2706 +
1.2707 + /**
1.2708 + * Makes a method handle which adapts a target method handle,
1.2709 + * by guarding it with a test, a boolean-valued method handle.
1.2710 + * If the guard fails, a fallback handle is called instead.
1.2711 + * All three method handles must have the same corresponding
1.2712 + * argument and return types, except that the return type
1.2713 + * of the test must be boolean, and the test is allowed
1.2714 + * to have fewer arguments than the other two method handles.
1.2715 + * <p> Here is pseudocode for the resulting adapter:
1.2716 + * <blockquote><pre>{@code
1.2717 + * boolean test(A...);
1.2718 + * T target(A...,B...);
1.2719 + * T fallback(A...,B...);
1.2720 + * T adapter(A... a,B... b) {
1.2721 + * if (test(a...))
1.2722 + * return target(a..., b...);
1.2723 + * else
1.2724 + * return fallback(a..., b...);
1.2725 + * }
1.2726 + * }</pre></blockquote>
1.2727 + * Note that the test arguments ({@code a...} in the pseudocode) cannot
1.2728 + * be modified by execution of the test, and so are passed unchanged
1.2729 + * from the caller to the target or fallback as appropriate.
1.2730 + * @param test method handle used for test, must return boolean
1.2731 + * @param target method handle to call if test passes
1.2732 + * @param fallback method handle to call if test fails
1.2733 + * @return method handle which incorporates the specified if/then/else logic
1.2734 + * @throws NullPointerException if any argument is null
1.2735 + * @throws IllegalArgumentException if {@code test} does not return boolean,
1.2736 + * or if all three method types do not match (with the return
1.2737 + * type of {@code test} changed to match that of the target).
1.2738 + */
1.2739 + public static
1.2740 + MethodHandle guardWithTest(MethodHandle test,
1.2741 + MethodHandle target,
1.2742 + MethodHandle fallback) {
1.2743 + MethodType gtype = test.type();
1.2744 + MethodType ttype = target.type();
1.2745 + MethodType ftype = fallback.type();
1.2746 + if (!ttype.equals(ftype))
1.2747 + throw misMatchedTypes("target and fallback types", ttype, ftype);
1.2748 + if (gtype.returnType() != boolean.class)
1.2749 + throw newIllegalArgumentException("guard type is not a predicate "+gtype);
1.2750 + List<Class<?>> targs = ttype.parameterList();
1.2751 + List<Class<?>> gargs = gtype.parameterList();
1.2752 + if (!targs.equals(gargs)) {
1.2753 + int gpc = gargs.size(), tpc = targs.size();
1.2754 + if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs))
1.2755 + throw misMatchedTypes("target and test types", ttype, gtype);
1.2756 + test = dropArguments(test, gpc, targs.subList(gpc, tpc));
1.2757 + gtype = test.type();
1.2758 + }
1.2759 + return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
1.2760 + }
1.2761 +
1.2762 + static RuntimeException misMatchedTypes(String what, MethodType t1, MethodType t2) {
1.2763 + return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
1.2764 + }
1.2765 +
1.2766 + /**
1.2767 + * Makes a method handle which adapts a target method handle,
1.2768 + * by running it inside an exception handler.
1.2769 + * If the target returns normally, the adapter returns that value.
1.2770 + * If an exception matching the specified type is thrown, the fallback
1.2771 + * handle is called instead on the exception, plus the original arguments.
1.2772 + * <p>
1.2773 + * The target and handler must have the same corresponding
1.2774 + * argument and return types, except that handler may omit trailing arguments
1.2775 + * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
1.2776 + * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
1.2777 + * <p> Here is pseudocode for the resulting adapter:
1.2778 + * <blockquote><pre>{@code
1.2779 + * T target(A..., B...);
1.2780 + * T handler(ExType, A...);
1.2781 + * T adapter(A... a, B... b) {
1.2782 + * try {
1.2783 + * return target(a..., b...);
1.2784 + * } catch (ExType ex) {
1.2785 + * return handler(ex, a...);
1.2786 + * }
1.2787 + * }
1.2788 + * }</pre></blockquote>
1.2789 + * Note that the saved arguments ({@code a...} in the pseudocode) cannot
1.2790 + * be modified by execution of the target, and so are passed unchanged
1.2791 + * from the caller to the handler, if the handler is invoked.
1.2792 + * <p>
1.2793 + * The target and handler must return the same type, even if the handler
1.2794 + * always throws. (This might happen, for instance, because the handler
1.2795 + * is simulating a {@code finally} clause).
1.2796 + * To create such a throwing handler, compose the handler creation logic
1.2797 + * with {@link #throwException throwException},
1.2798 + * in order to create a method handle of the correct return type.
1.2799 + * @param target method handle to call
1.2800 + * @param exType the type of exception which the handler will catch
1.2801 + * @param handler method handle to call if a matching exception is thrown
1.2802 + * @return method handle which incorporates the specified try/catch logic
1.2803 + * @throws NullPointerException if any argument is null
1.2804 + * @throws IllegalArgumentException if {@code handler} does not accept
1.2805 + * the given exception type, or if the method handle types do
1.2806 + * not match in their return types and their
1.2807 + * corresponding parameters
1.2808 + */
1.2809 + public static
1.2810 + MethodHandle catchException(MethodHandle target,
1.2811 + Class<? extends Throwable> exType,
1.2812 + MethodHandle handler) {
1.2813 + MethodType ttype = target.type();
1.2814 + MethodType htype = handler.type();
1.2815 + if (htype.parameterCount() < 1 ||
1.2816 + !htype.parameterType(0).isAssignableFrom(exType))
1.2817 + throw newIllegalArgumentException("handler does not accept exception type "+exType);
1.2818 + if (htype.returnType() != ttype.returnType())
1.2819 + throw misMatchedTypes("target and handler return types", ttype, htype);
1.2820 + List<Class<?>> targs = ttype.parameterList();
1.2821 + List<Class<?>> hargs = htype.parameterList();
1.2822 + hargs = hargs.subList(1, hargs.size()); // omit leading parameter from handler
1.2823 + if (!targs.equals(hargs)) {
1.2824 + int hpc = hargs.size(), tpc = targs.size();
1.2825 + if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
1.2826 + throw misMatchedTypes("target and handler types", ttype, htype);
1.2827 + handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc));
1.2828 + htype = handler.type();
1.2829 + }
1.2830 + return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
1.2831 + }
1.2832 +
1.2833 + /**
1.2834 + * Produces a method handle which will throw exceptions of the given {@code exType}.
1.2835 + * The method handle will accept a single argument of {@code exType},
1.2836 + * and immediately throw it as an exception.
1.2837 + * The method type will nominally specify a return of {@code returnType}.
1.2838 + * The return type may be anything convenient: It doesn't matter to the
1.2839 + * method handle's behavior, since it will never return normally.
1.2840 + * @param returnType the return type of the desired method handle
1.2841 + * @param exType the parameter type of the desired method handle
1.2842 + * @return method handle which can throw the given exceptions
1.2843 + * @throws NullPointerException if either argument is null
1.2844 + */
1.2845 + public static
1.2846 + MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
1.2847 + if (!Throwable.class.isAssignableFrom(exType))
1.2848 + throw new ClassCastException(exType.getName());
1.2849 + return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType));
1.2850 + }
1.2851 +}