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