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