1 /* 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. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import java.lang.reflect.*; 29 import java.security.AccessController; 30 import java.security.PrivilegedAction; 31 import java.util.List; 32 import java.util.ArrayList; 33 import java.util.Arrays; 34 import sun.invoke.util.ValueConversions; 35 import sun.invoke.util.VerifyAccess; 36 import sun.invoke.util.Wrapper; 37 import sun.reflect.CallerSensitive; 38 import sun.reflect.Reflection; 39 import sun.security.util.SecurityConstants; 40 import static java.lang.invoke.MethodHandleStatics.*; 41 import static java.lang.invoke.MethodHandleNatives.Constants.*; 42 43 /** 44 * This class consists exclusively of static methods that operate on or return 45 * method handles. They fall into several categories: 46 * <ul> 47 * <li>Lookup methods which help create method handles for methods and fields. 48 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 49 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 50 * <li>Wrapper methods which can convert between method handles and interface types. 51 * </ul> 52 * <p> 53 * @author John Rose, JSR 292 EG 54 */ 55 public class MethodHandles { 56 57 private MethodHandles() { } // do not instantiate 58 59 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 60 static { MethodHandleImpl.initStatics(); } 61 // See IMPL_LOOKUP below. 62 63 //// Method handle creation from ordinary methods. 64 65 /** 66 * Returns a {@link Lookup lookup object} on the caller, 67 * which has the capability to access any method handle that the caller has access to, 68 * including direct method handles to private fields and methods. 69 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 70 * Do not store it in place where untrusted code can access it. 71 */ 72 @CallerSensitive 73 public static Lookup lookup() { 74 return new Lookup(Reflection.getCallerClass()); 75 } 76 77 /** 78 * Returns a {@link Lookup lookup object} which is trusted minimally. 79 * It can only be used to create method handles to 80 * publicly accessible fields and methods. 81 * <p> 82 * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class} 83 * of this lookup object will be {@link java.lang.Object}. 84 * <p> 85 * The lookup class can be changed to any other class {@code C} using an expression of the form 86 * {@linkplain Lookup#in <code>publicLookup().in(C.class)</code>}. 87 * Since all classes have equal access to public names, 88 * such a change would confer no new access rights. 89 */ 90 public static Lookup publicLookup() { 91 return Lookup.PUBLIC_LOOKUP; 92 } 93 94 /** 95 * A <em>lookup object</em> is a factory for creating method handles, 96 * when the creation requires access checking. 97 * Method handles do not perform 98 * access checks when they are called, but rather when they are created. 99 * Therefore, method handle access 100 * restrictions must be enforced when a method handle is created. 101 * The caller class against which those restrictions are enforced 102 * is known as the {@linkplain #lookupClass lookup class}. 103 * <p> 104 * A lookup class which needs to create method handles will call 105 * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself. 106 * When the {@code Lookup} factory object is created, the identity of the lookup class is 107 * determined, and securely stored in the {@code Lookup} object. 108 * The lookup class (or its delegates) may then use factory methods 109 * on the {@code Lookup} object to create method handles for access-checked members. 110 * This includes all methods, constructors, and fields which are allowed to the lookup class, 111 * even private ones. 112 * <p> 113 * The factory methods on a {@code Lookup} object correspond to all major 114 * use cases for methods, constructors, and fields. 115 * Here is a summary of the correspondence between these factory methods and 116 * the behavior the resulting method handles: 117 * <code> 118 * <table border=1 cellpadding=5 summary="lookup method behaviors"> 119 * <tr><th>lookup expression</th><th>member</th><th>behavior</th></tr> 120 * <tr> 121 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td> 122 * <td>FT f;</td><td>(T) this.f;</td> 123 * </tr> 124 * <tr> 125 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td> 126 * <td>static<br>FT f;</td><td>(T) C.f;</td> 127 * </tr> 128 * <tr> 129 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td> 130 * <td>FT f;</td><td>this.f = x;</td> 131 * </tr> 132 * <tr> 133 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td> 134 * <td>static<br>FT f;</td><td>C.f = arg;</td> 135 * </tr> 136 * <tr> 137 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td> 138 * <td>T m(A*);</td><td>(T) this.m(arg*);</td> 139 * </tr> 140 * <tr> 141 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td> 142 * <td>static<br>T m(A*);</td><td>(T) C.m(arg*);</td> 143 * </tr> 144 * <tr> 145 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td> 146 * <td>T m(A*);</td><td>(T) super.m(arg*);</td> 147 * </tr> 148 * <tr> 149 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td> 150 * <td>C(A*);</td><td>(T) new C(arg*);</td> 151 * </tr> 152 * <tr> 153 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td> 154 * <td>(static)?<br>FT f;</td><td>(FT) aField.get(thisOrNull);</td> 155 * </tr> 156 * <tr> 157 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td> 158 * <td>(static)?<br>FT f;</td><td>aField.set(thisOrNull, arg);</td> 159 * </tr> 160 * <tr> 161 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 162 * <td>(static)?<br>T m(A*);</td><td>(T) aMethod.invoke(thisOrNull, arg*);</td> 163 * </tr> 164 * <tr> 165 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td> 166 * <td>C(A*);</td><td>(C) aConstructor.newInstance(arg*);</td> 167 * </tr> 168 * <tr> 169 * <td>{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 170 * <td>(static)?<br>T m(A*);</td><td>(T) aMethod.invoke(thisOrNull, arg*);</td> 171 * </tr> 172 * </table> 173 * </code> 174 * Here, the type {@code C} is the class or interface being searched for a member, 175 * documented as a parameter named {@code refc} in the lookup methods. 176 * The method or constructor type {@code MT} is composed from the return type {@code T} 177 * and the sequence of argument types {@code A*}. 178 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 179 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 180 * if it is present, it is always the leading argument to the method handle invocation. 181 * (In the case of some {@code protected} members, {@code this} may be 182 * restricted in type to the lookup class; see below.) 183 * The name {@code arg} stands for all the other method handle arguments. 184 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 185 * stands for a null reference if the accessed method or field is static, 186 * and {@code this} otherwise. 187 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 188 * for reflective objects corresponding to the given members. 189 * <p> 190 * In cases where the given member is of variable arity (i.e., a method or constructor) 191 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 192 * In all other cases, the returned method handle will be of fixed arity. 193 * <p> 194 * The equivalence between looked-up method handles and underlying 195 * class members can break down in a few ways: 196 * <ul> 197 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 198 * the lookup can still succeed, even when there is no equivalent 199 * Java expression or bytecoded constant. 200 * <li>Likewise, if {@code T} or {@code MT} 201 * is not symbolically accessible from the lookup class's loader, 202 * the lookup can still succeed. 203 * For example, lookups for {@code MethodHandle.invokeExact} and 204 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 205 * <li>If there is a security manager installed, it can forbid the lookup 206 * on various grounds (<a href="#secmgr">see below</a>). 207 * By contrast, the {@code ldc} instruction is not subject to 208 * security manager checks. 209 * </ul> 210 * 211 * <h3><a name="access"></a>Access checking</h3> 212 * Access checks are applied in the factory methods of {@code Lookup}, 213 * when a method handle is created. 214 * This is a key difference from the Core Reflection API, since 215 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 216 * performs access checking against every caller, on every call. 217 * <p> 218 * All access checks start from a {@code Lookup} object, which 219 * compares its recorded lookup class against all requests to 220 * create method handles. 221 * A single {@code Lookup} object can be used to create any number 222 * of access-checked method handles, all checked against a single 223 * lookup class. 224 * <p> 225 * A {@code Lookup} object can be shared with other trusted code, 226 * such as a metaobject protocol. 227 * A shared {@code Lookup} object delegates the capability 228 * to create method handles on private members of the lookup class. 229 * Even if privileged code uses the {@code Lookup} object, 230 * the access checking is confined to the privileges of the 231 * original lookup class. 232 * <p> 233 * A lookup can fail, because 234 * the containing class is not accessible to the lookup class, or 235 * because the desired class member is missing, or because the 236 * desired class member is not accessible to the lookup class. 237 * In any of these cases, a {@code ReflectiveOperationException} will be 238 * thrown from the attempted lookup. The exact class will be one of 239 * the following: 240 * <ul> 241 * <li>NoSuchMethodException — if a method is requested but does not exist 242 * <li>NoSuchFieldException — if a field is requested but does not exist 243 * <li>IllegalAccessException — if the member exists but an access check fails 244 * </ul> 245 * <p> 246 * In general, the conditions under which a method handle may be 247 * looked up for a method {@code M} are exactly equivalent to the conditions 248 * under which the lookup class could have compiled and resolved a call to {@code M}. 249 * And the effect of invoking the method handle resulting from the lookup 250 * is exactly equivalent to executing the compiled and resolved call to {@code M}. 251 * The same point is true of fields and constructors. 252 * <p> 253 * If the desired member is {@code protected}, the usual JVM rules apply, 254 * including the requirement that the lookup class must be either be in the 255 * same package as the desired member, or must inherit that member. 256 * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.) 257 * In addition, if the desired member is a non-static field or method 258 * in a different package, the resulting method handle may only be applied 259 * to objects of the lookup class or one of its subclasses. 260 * This requirement is enforced by narrowing the type of the leading 261 * {@code this} parameter from {@code C} 262 * (which will necessarily be a superclass of the lookup class) 263 * to the lookup class itself. 264 * <p> 265 * In some cases, access between nested classes is obtained by the Java compiler by creating 266 * an wrapper method to access a private method of another class 267 * in the same top-level declaration. 268 * For example, a nested class {@code C.D} 269 * can access private members within other related classes such as 270 * {@code C}, {@code C.D.E}, or {@code C.B}, 271 * but the Java compiler may need to generate wrapper methods in 272 * those related classes. In such cases, a {@code Lookup} object on 273 * {@code C.E} would be unable to those private members. 274 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 275 * which can transform a lookup on {@code C.E} into one on any of those other 276 * classes, without special elevation of privilege. 277 * <p> 278 * Although bytecode instructions can only refer to classes in 279 * a related class loader, this API can search for methods in any 280 * class, as long as a reference to its {@code Class} object is 281 * available. Such cross-loader references are also possible with the 282 * Core Reflection API, and are impossible to bytecode instructions 283 * such as {@code invokestatic} or {@code getfield}. 284 * There is a {@linkplain java.lang.SecurityManager security manager API} 285 * to allow applications to check such cross-loader references. 286 * These checks apply to both the {@code MethodHandles.Lookup} API 287 * and the Core Reflection API 288 * (as found on {@link java.lang.Class Class}). 289 * <p> 290 * Access checks only apply to named and reflected methods, 291 * constructors, and fields. 292 * Other method handle creation methods, such as 293 * {@link MethodHandle#asType MethodHandle.asType}, 294 * do not require any access checks, and are done 295 * with static methods of {@link MethodHandles}, 296 * independently of any {@code Lookup} object. 297 * 298 * <h3>Security manager interactions</h3> 299 * <a name="secmgr"></a> 300 * If a security manager is present, member lookups are subject to 301 * additional checks. 302 * From one to four calls are made to the security manager. 303 * Any of these calls can refuse access by throwing a 304 * {@link java.lang.SecurityException SecurityException}. 305 * Define {@code smgr} as the security manager, 306 * {@code refc} as the containing class in which the member 307 * is being sought, and {@code defc} as the class in which the 308 * member is actually defined. 309 * The calls are made according to the following rules: 310 * <ul> 311 * <li>In all cases, {@link SecurityManager#checkMemberAccess 312 * smgr.checkMemberAccess(refc, Member.PUBLIC)} is called. 313 * <li>If the class loader of the lookup class is not 314 * the same as or an ancestor of the class loader of {@code refc}, 315 * then {@link SecurityManager#checkPackageAccess 316 * smgr.checkPackageAccess(refcPkg)} is called, 317 * where {@code refcPkg} is the package of {@code refc}. 318 * <li>If the retrieved member is not public, 319 * {@link SecurityManager#checkMemberAccess 320 * smgr.checkMemberAccess(defc, Member.DECLARED)} is called. 321 * (Note that {@code defc} might be the same as {@code refc}.) 322 * The default implementation of this security manager method 323 * inspects the stack to determine the original caller of 324 * the reflective request (such as {@code findStatic}), 325 * and performs additional permission checks if the 326 * class loader of {@code defc} differs from the class 327 * loader of the class from which the reflective request came. 328 * <li>If the retrieved member is not public, 329 * and if {@code defc} and {@code refc} are in different class loaders, 330 * and if the class loader of the lookup class is not 331 * the same as or an ancestor of the class loader of {@code defc}, 332 * then {@link SecurityManager#checkPackageAccess 333 * smgr.checkPackageAccess(defcPkg)} is called, 334 * where {@code defcPkg} is the package of {@code defc}. 335 * </ul> 336 */ 337 // FIXME in MR1: clarify that the bytecode behavior of a caller-ID method (like Class.forName) is relative to the lookupClass used to create the method handle, not the dynamic caller of the method handle 338 public static final 339 class Lookup { 340 /** The class on behalf of whom the lookup is being performed. */ 341 private final Class<?> lookupClass; 342 343 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 344 private final int allowedModes; 345 346 /** A single-bit mask representing {@code public} access, 347 * which may contribute to the result of {@link #lookupModes lookupModes}. 348 * The value, {@code 0x01}, happens to be the same as the value of the 349 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 350 */ 351 public static final int PUBLIC = Modifier.PUBLIC; 352 353 /** A single-bit mask representing {@code private} access, 354 * which may contribute to the result of {@link #lookupModes lookupModes}. 355 * The value, {@code 0x02}, happens to be the same as the value of the 356 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 357 */ 358 public static final int PRIVATE = Modifier.PRIVATE; 359 360 /** A single-bit mask representing {@code protected} access, 361 * which may contribute to the result of {@link #lookupModes lookupModes}. 362 * The value, {@code 0x04}, happens to be the same as the value of the 363 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 364 */ 365 public static final int PROTECTED = Modifier.PROTECTED; 366 367 /** A single-bit mask representing {@code package} access (default access), 368 * which may contribute to the result of {@link #lookupModes lookupModes}. 369 * The value is {@code 0x08}, which does not correspond meaningfully to 370 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 371 */ 372 public static final int PACKAGE = Modifier.STATIC; 373 374 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE); 375 private static final int TRUSTED = -1; 376 377 private static int fixmods(int mods) { 378 mods &= (ALL_MODES - PACKAGE); 379 return (mods != 0) ? mods : PACKAGE; 380 } 381 382 /** Tells which class is performing the lookup. It is this class against 383 * which checks are performed for visibility and access permissions. 384 * <p> 385 * The class implies a maximum level of access permission, 386 * but the permissions may be additionally limited by the bitmask 387 * {@link #lookupModes lookupModes}, which controls whether non-public members 388 * can be accessed. 389 */ 390 public Class<?> lookupClass() { 391 return lookupClass; 392 } 393 394 // This is just for calling out to MethodHandleImpl. 395 private Class<?> lookupClassOrNull() { 396 return (allowedModes == TRUSTED) ? null : lookupClass; 397 } 398 399 /** Tells which access-protection classes of members this lookup object can produce. 400 * The result is a bit-mask of the bits 401 * {@linkplain #PUBLIC PUBLIC (0x01)}, 402 * {@linkplain #PRIVATE PRIVATE (0x02)}, 403 * {@linkplain #PROTECTED PROTECTED (0x04)}, 404 * and {@linkplain #PACKAGE PACKAGE (0x08)}. 405 * <p> 406 * A freshly-created lookup object 407 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} 408 * has all possible bits set, since the caller class can access all its own members. 409 * A lookup object on a new lookup class 410 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 411 * may have some mode bits set to zero. 412 * The purpose of this is to restrict access via the new lookup object, 413 * so that it can access only names which can be reached by the original 414 * lookup object, and also by the new lookup class. 415 */ 416 public int lookupModes() { 417 return allowedModes & ALL_MODES; 418 } 419 420 /** Embody the current class (the lookupClass) as a lookup class 421 * for method handle creation. 422 * Must be called by from a method in this package, 423 * which in turn is called by a method not in this package. 424 */ 425 Lookup(Class<?> lookupClass) { 426 this(lookupClass, ALL_MODES); 427 // make sure we haven't accidentally picked up a privileged class: 428 checkUnprivilegedlookupClass(lookupClass); 429 } 430 431 private Lookup(Class<?> lookupClass, int allowedModes) { 432 this.lookupClass = lookupClass; 433 this.allowedModes = allowedModes; 434 } 435 436 /** 437 * Creates a lookup on the specified new lookup class. 438 * The resulting object will report the specified 439 * class as its own {@link #lookupClass lookupClass}. 440 * <p> 441 * However, the resulting {@code Lookup} object is guaranteed 442 * to have no more access capabilities than the original. 443 * In particular, access capabilities can be lost as follows:<ul> 444 * <li>If the new lookup class differs from the old one, 445 * protected members will not be accessible by virtue of inheritance. 446 * (Protected members may continue to be accessible because of package sharing.) 447 * <li>If the new lookup class is in a different package 448 * than the old one, protected and default (package) members will not be accessible. 449 * <li>If the new lookup class is not within the same package member 450 * as the old one, private members will not be accessible. 451 * <li>If the new lookup class is not accessible to the old lookup class, 452 * then no members, not even public members, will be accessible. 453 * (In all other cases, public members will continue to be accessible.) 454 * </ul> 455 * 456 * @param requestedLookupClass the desired lookup class for the new lookup object 457 * @return a lookup object which reports the desired lookup class 458 * @throws NullPointerException if the argument is null 459 */ 460 public Lookup in(Class<?> requestedLookupClass) { 461 requestedLookupClass.getClass(); // null check 462 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 463 return new Lookup(requestedLookupClass, ALL_MODES); 464 if (requestedLookupClass == this.lookupClass) 465 return this; // keep same capabilities 466 int newModes = (allowedModes & (ALL_MODES & ~PROTECTED)); 467 if ((newModes & PACKAGE) != 0 468 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 469 newModes &= ~(PACKAGE|PRIVATE); 470 } 471 // Allow nestmate lookups to be created without special privilege: 472 if ((newModes & PRIVATE) != 0 473 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 474 newModes &= ~PRIVATE; 475 } 476 if ((newModes & PUBLIC) != 0 477 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) { 478 // The requested class it not accessible from the lookup class. 479 // No permissions. 480 newModes = 0; 481 } 482 checkUnprivilegedlookupClass(requestedLookupClass); 483 return new Lookup(requestedLookupClass, newModes); 484 } 485 486 // Make sure outer class is initialized first. 487 static { IMPL_NAMES.getClass(); } 488 489 /** Version of lookup which is trusted minimally. 490 * It can only be used to create method handles to 491 * publicly accessible members. 492 */ 493 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC); 494 495 /** Package-private version of lookup which is trusted. */ 496 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED); 497 498 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 499 String name = lookupClass.getName(); 500 if (name.startsWith("java.lang.invoke.")) 501 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 502 } 503 504 /** 505 * Displays the name of the class from which lookups are to be made. 506 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 507 * If there are restrictions on the access permitted to this lookup, 508 * this is indicated by adding a suffix to the class name, consisting 509 * of a slash and a keyword. The keyword represents the strongest 510 * allowed access, and is chosen as follows: 511 * <ul> 512 * <li>If no access is allowed, the suffix is "/noaccess". 513 * <li>If only public access is allowed, the suffix is "/public". 514 * <li>If only public and package access are allowed, the suffix is "/package". 515 * <li>If only public, package, and private access are allowed, the suffix is "/private". 516 * </ul> 517 * If none of the above cases apply, it is the case that full 518 * access (public, package, private, and protected) is allowed. 519 * In this case, no suffix is added. 520 * This is true only of an object obtained originally from 521 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 522 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 523 * always have restricted access, and will display a suffix. 524 * <p> 525 * (It may seem strange that protected access should be 526 * stronger than private access. Viewed independently from 527 * package access, protected access is the first to be lost, 528 * because it requires a direct subclass relationship between 529 * caller and callee.) 530 * @see #in 531 */ 532 @Override 533 public String toString() { 534 String cname = lookupClass.getName(); 535 switch (allowedModes) { 536 case 0: // no privileges 537 return cname + "/noaccess"; 538 case PUBLIC: 539 return cname + "/public"; 540 case PUBLIC|PACKAGE: 541 return cname + "/package"; 542 case ALL_MODES & ~PROTECTED: 543 return cname + "/private"; 544 case ALL_MODES: 545 return cname; 546 case TRUSTED: 547 return "/trusted"; // internal only; not exported 548 default: // Should not happen, but it's a bitfield... 549 cname = cname + "/" + Integer.toHexString(allowedModes); 550 assert(false) : cname; 551 return cname; 552 } 553 } 554 555 /** 556 * Produces a method handle for a static method. 557 * The type of the method handle will be that of the method. 558 * (Since static methods do not take receivers, there is no 559 * additional receiver argument inserted into the method handle type, 560 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 561 * The method and all its argument types must be accessible to the lookup class. 562 * If the method's class has not yet been initialized, that is done 563 * immediately, before the method handle is returned. 564 * <p> 565 * The returned method handle will have 566 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 567 * the method's variable arity modifier bit ({@code 0x0080}) is set. 568 * @param refc the class from which the method is accessed 569 * @param name the name of the method 570 * @param type the type of the method 571 * @return the desired method handle 572 * @throws NoSuchMethodException if the method does not exist 573 * @throws IllegalAccessException if access checking fails, 574 * or if the method is not {@code static}, 575 * or if the method's variable arity modifier bit 576 * is set and {@code asVarargsCollector} fails 577 * @exception SecurityException if a security manager is present and it 578 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 579 * @throws NullPointerException if any argument is null 580 */ 581 @CallerSensitive 582 public 583 MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 584 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 585 Class<?> callerClass = Reflection.getCallerClass(); 586 checkSecurityManager(refc, method, callerClass); 587 return getDirectMethod(REF_invokeStatic, refc, method, 588 findBoundCallerClass(method, callerClass)); 589 } 590 591 /** 592 * Produces a method handle for a virtual method. 593 * The type of the method handle will be that of the method, 594 * with the receiver type (usually {@code refc}) prepended. 595 * The method and all its argument types must be accessible to the lookup class. 596 * <p> 597 * When called, the handle will treat the first argument as a receiver 598 * and dispatch on the receiver's type to determine which method 599 * implementation to enter. 600 * (The dispatching action is identical with that performed by an 601 * {@code invokevirtual} or {@code invokeinterface} instruction.) 602 * <p> 603 * The first argument will be of type {@code refc} if the lookup 604 * class has full privileges to access the member. Otherwise 605 * the member must be {@code protected} and the first argument 606 * will be restricted in type to the lookup class. 607 * <p> 608 * The returned method handle will have 609 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 610 * the method's variable arity modifier bit ({@code 0x0080}) is set. 611 * <p> 612 * Because of the general equivalence between {@code invokevirtual} 613 * instructions and method handles produced by {@code findVirtual}, 614 * if the class is {@code MethodHandle} and the name string is 615 * {@code invokeExact} or {@code invoke}, the resulting 616 * method handle is equivalent to one produced by 617 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 618 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 619 * with the same {@code type} argument. 620 * 621 * @param refc the class or interface from which the method is accessed 622 * @param name the name of the method 623 * @param type the type of the method, with the receiver argument omitted 624 * @return the desired method handle 625 * @throws NoSuchMethodException if the method does not exist 626 * @throws IllegalAccessException if access checking fails, 627 * or if the method is {@code static} 628 * or if the method's variable arity modifier bit 629 * is set and {@code asVarargsCollector} fails 630 * @exception SecurityException if a security manager is present and it 631 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 632 * @throws NullPointerException if any argument is null 633 */ 634 @CallerSensitive 635 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 636 if (refc == MethodHandle.class) { 637 MethodHandle mh = findVirtualForMH(name, type); 638 if (mh != null) return mh; 639 } 640 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 641 MemberName method = resolveOrFail(refKind, refc, name, type); 642 Class<?> callerClass = Reflection.getCallerClass(); 643 checkSecurityManager(refc, method, callerClass); 644 return getDirectMethod(refKind, refc, method, 645 findBoundCallerClass(method, callerClass)); 646 } 647 private MethodHandle findVirtualForMH(String name, MethodType type) { 648 // these names require special lookups because of the implicit MethodType argument 649 if ("invoke".equals(name)) 650 return invoker(type); 651 if ("invokeExact".equals(name)) 652 return exactInvoker(type); 653 return null; 654 } 655 656 /** 657 * Produces a method handle which creates an object and initializes it, using 658 * the constructor of the specified type. 659 * The parameter types of the method handle will be those of the constructor, 660 * while the return type will be a reference to the constructor's class. 661 * The constructor and all its argument types must be accessible to the lookup class. 662 * If the constructor's class has not yet been initialized, that is done 663 * immediately, before the method handle is returned. 664 * <p> 665 * Note: The requested type must have a return type of {@code void}. 666 * This is consistent with the JVM's treatment of constructor type descriptors. 667 * <p> 668 * The returned method handle will have 669 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 670 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 671 * @param refc the class or interface from which the method is accessed 672 * @param type the type of the method, with the receiver argument omitted, and a void return type 673 * @return the desired method handle 674 * @throws NoSuchMethodException if the constructor does not exist 675 * @throws IllegalAccessException if access checking fails 676 * or if the method's variable arity modifier bit 677 * is set and {@code asVarargsCollector} fails 678 * @exception SecurityException if a security manager is present and it 679 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 680 * @throws NullPointerException if any argument is null 681 */ 682 @CallerSensitive 683 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 684 String name = "<init>"; 685 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 686 checkSecurityManager(refc, ctor, Reflection.getCallerClass()); 687 return getDirectConstructor(refc, ctor); 688 } 689 690 /** 691 * Produces an early-bound method handle for a virtual method, 692 * as if called from an {@code invokespecial} 693 * instruction from {@code caller}. 694 * The type of the method handle will be that of the method, 695 * with a suitably restricted receiver type (such as {@code caller}) prepended. 696 * The method and all its argument types must be accessible 697 * to the caller. 698 * <p> 699 * When called, the handle will treat the first argument as a receiver, 700 * but will not dispatch on the receiver's type. 701 * (This direct invocation action is identical with that performed by an 702 * {@code invokespecial} instruction.) 703 * <p> 704 * If the explicitly specified caller class is not identical with the 705 * lookup class, or if this lookup object does not have private access 706 * privileges, the access fails. 707 * <p> 708 * The returned method handle will have 709 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 710 * the method's variable arity modifier bit ({@code 0x0080}) is set. 711 * @param refc the class or interface from which the method is accessed 712 * @param name the name of the method (which must not be "<init>") 713 * @param type the type of the method, with the receiver argument omitted 714 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 715 * @return the desired method handle 716 * @throws NoSuchMethodException if the method does not exist 717 * @throws IllegalAccessException if access checking fails 718 * or if the method's variable arity modifier bit 719 * is set and {@code asVarargsCollector} fails 720 * @exception SecurityException if a security manager is present and it 721 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 722 * @throws NullPointerException if any argument is null 723 */ 724 @CallerSensitive 725 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 726 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 727 checkSpecialCaller(specialCaller); 728 Lookup specialLookup = this.in(specialCaller); 729 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 730 Class<?> callerClass = Reflection.getCallerClass(); 731 checkSecurityManager(refc, method, callerClass); 732 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, 733 findBoundCallerClass(method, callerClass)); 734 } 735 736 /** 737 * Produces a method handle giving read access to a non-static field. 738 * The type of the method handle will have a return type of the field's 739 * value type. 740 * The method handle's single argument will be the instance containing 741 * the field. 742 * Access checking is performed immediately on behalf of the lookup class. 743 * @param refc the class or interface from which the method is accessed 744 * @param name the field's name 745 * @param type the field's type 746 * @return a method handle which can load values from the field 747 * @throws NoSuchFieldException if the field does not exist 748 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 749 * @exception SecurityException if a security manager is present and it 750 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 751 * @throws NullPointerException if any argument is null 752 */ 753 @CallerSensitive 754 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 755 MemberName field = resolveOrFail(REF_getField, refc, name, type); 756 checkSecurityManager(refc, field, Reflection.getCallerClass()); 757 return getDirectField(REF_getField, refc, field); 758 } 759 760 /** 761 * Produces a method handle giving write access to a non-static field. 762 * The type of the method handle will have a void return type. 763 * The method handle will take two arguments, the instance containing 764 * the field, and the value to be stored. 765 * The second argument will be of the field's value type. 766 * Access checking is performed immediately on behalf of the lookup class. 767 * @param refc the class or interface from which the method is accessed 768 * @param name the field's name 769 * @param type the field's type 770 * @return a method handle which can store values into the field 771 * @throws NoSuchFieldException if the field does not exist 772 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 773 * @exception SecurityException if a security manager is present and it 774 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 775 * @throws NullPointerException if any argument is null 776 */ 777 @CallerSensitive 778 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 779 MemberName field = resolveOrFail(REF_putField, refc, name, type); 780 checkSecurityManager(refc, field, Reflection.getCallerClass()); 781 return getDirectField(REF_putField, refc, field); 782 } 783 784 /** 785 * Produces a method handle giving read access to a static field. 786 * The type of the method handle will have a return type of the field's 787 * value type. 788 * The method handle will take no arguments. 789 * Access checking is performed immediately on behalf of the lookup class. 790 * @param refc the class or interface from which the method is accessed 791 * @param name the field's name 792 * @param type the field's type 793 * @return a method handle which can load values from the field 794 * @throws NoSuchFieldException if the field does not exist 795 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 796 * @exception SecurityException if a security manager is present and it 797 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 798 * @throws NullPointerException if any argument is null 799 */ 800 @CallerSensitive 801 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 802 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 803 checkSecurityManager(refc, field, Reflection.getCallerClass()); 804 return getDirectField(REF_getStatic, refc, field); 805 } 806 807 /** 808 * Produces a method handle giving write access to a static field. 809 * The type of the method handle will have a void return type. 810 * The method handle will take a single 811 * argument, of the field's value type, the value to be stored. 812 * Access checking is performed immediately on behalf of the lookup class. 813 * @param refc the class or interface from which the method is accessed 814 * @param name the field's name 815 * @param type the field's type 816 * @return a method handle which can store values into the field 817 * @throws NoSuchFieldException if the field does not exist 818 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 819 * @exception SecurityException if a security manager is present and it 820 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 821 * @throws NullPointerException if any argument is null 822 */ 823 @CallerSensitive 824 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 825 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 826 checkSecurityManager(refc, field, Reflection.getCallerClass()); 827 return getDirectField(REF_putStatic, refc, field); 828 } 829 830 /** 831 * Produces an early-bound method handle for a non-static method. 832 * The receiver must have a supertype {@code defc} in which a method 833 * of the given name and type is accessible to the lookup class. 834 * The method and all its argument types must be accessible to the lookup class. 835 * The type of the method handle will be that of the method, 836 * without any insertion of an additional receiver parameter. 837 * The given receiver will be bound into the method handle, 838 * so that every call to the method handle will invoke the 839 * requested method on the given receiver. 840 * <p> 841 * The returned method handle will have 842 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 843 * the method's variable arity modifier bit ({@code 0x0080}) is set 844 * <em>and</em> the trailing array argument is not the only argument. 845 * (If the trailing array argument is the only argument, 846 * the given receiver value will be bound to it.) 847 * <p> 848 * This is equivalent to the following code: 849 * <blockquote><pre> 850 import static java.lang.invoke.MethodHandles.*; 851 import static java.lang.invoke.MethodType.*; 852 ... 853 MethodHandle mh0 = lookup().{@link #findVirtual findVirtual}(defc, name, type); 854 MethodHandle mh1 = mh0.{@link MethodHandle#bindTo bindTo}(receiver); 855 MethodType mt1 = mh1.type(); 856 if (mh0.isVarargsCollector()) 857 mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1)); 858 return mh1; 859 * </pre></blockquote> 860 * where {@code defc} is either {@code receiver.getClass()} or a super 861 * type of that class, in which the requested method is accessible 862 * to the lookup class. 863 * (Note that {@code bindTo} does not preserve variable arity.) 864 * @param receiver the object from which the method is accessed 865 * @param name the name of the method 866 * @param type the type of the method, with the receiver argument omitted 867 * @return the desired method handle 868 * @throws NoSuchMethodException if the method does not exist 869 * @throws IllegalAccessException if access checking fails 870 * or if the method's variable arity modifier bit 871 * is set and {@code asVarargsCollector} fails 872 * @exception SecurityException if a security manager is present and it 873 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 874 * @throws NullPointerException if any argument is null 875 */ 876 @CallerSensitive 877 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 878 Class<? extends Object> refc = receiver.getClass(); // may get NPE 879 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 880 Class<?> callerClass = Reflection.getCallerClass(); 881 checkSecurityManager(refc, method, callerClass); 882 MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, 883 findBoundCallerClass(method, callerClass)); 884 return mh.bindReceiver(receiver).setVarargs(method); 885 } 886 887 /** 888 * Makes a direct method handle to <i>m</i>, if the lookup class has permission. 889 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 890 * If <i>m</i> is virtual, overriding is respected on every call. 891 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 892 * The type of the method handle will be that of the method, 893 * with the receiver type prepended (but only if it is non-static). 894 * If the method's {@code accessible} flag is not set, 895 * access checking is performed immediately on behalf of the lookup class. 896 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 897 * <p> 898 * The returned method handle will have 899 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 900 * the method's variable arity modifier bit ({@code 0x0080}) is set. 901 * @param m the reflected method 902 * @return a method handle which can invoke the reflected method 903 * @throws IllegalAccessException if access checking fails 904 * or if the method's variable arity modifier bit 905 * is set and {@code asVarargsCollector} fails 906 * @throws NullPointerException if the argument is null 907 */ 908 @CallerSensitive 909 public MethodHandle unreflect(Method m) throws IllegalAccessException { 910 MemberName method = new MemberName(m); 911 byte refKind = method.getReferenceKind(); 912 if (refKind == REF_invokeSpecial) 913 refKind = REF_invokeVirtual; 914 assert(method.isMethod()); 915 Class<?> callerClass = findBoundCallerClass(method, Reflection.getCallerClass()); 916 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 917 return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, callerClass); 918 } 919 920 /** 921 * Produces a method handle for a reflected method. 922 * It will bypass checks for overriding methods on the receiver, 923 * as if by a {@code invokespecial} instruction from within the {@code specialCaller}. 924 * The type of the method handle will be that of the method, 925 * with the special caller type prepended (and <em>not</em> the receiver of the method). 926 * If the method's {@code accessible} flag is not set, 927 * access checking is performed immediately on behalf of the lookup class, 928 * as if {@code invokespecial} instruction were being linked. 929 * <p> 930 * The returned method handle will have 931 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 932 * the method's variable arity modifier bit ({@code 0x0080}) is set. 933 * @param m the reflected method 934 * @param specialCaller the class nominally calling the method 935 * @return a method handle which can invoke the reflected method 936 * @throws IllegalAccessException if access checking fails 937 * or if the method's variable arity modifier bit 938 * is set and {@code asVarargsCollector} fails 939 * @throws NullPointerException if any argument is null 940 */ 941 @CallerSensitive 942 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 943 checkSpecialCaller(specialCaller); 944 Lookup specialLookup = this.in(specialCaller); 945 MemberName method = new MemberName(m, true); 946 assert(method.isMethod()); 947 Class<?> callerClass = findBoundCallerClass(method, Reflection.getCallerClass()); 948 // ignore m.isAccessible: this is a new kind of access 949 return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, callerClass); 950 } 951 952 /** 953 * Produces a method handle for a reflected constructor. 954 * The type of the method handle will be that of the constructor, 955 * with the return type changed to the declaring class. 956 * The method handle will perform a {@code newInstance} operation, 957 * creating a new instance of the constructor's class on the 958 * arguments passed to the method handle. 959 * <p> 960 * If the constructor's {@code accessible} flag is not set, 961 * access checking is performed immediately on behalf of the lookup class. 962 * <p> 963 * The returned method handle will have 964 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 965 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 966 * @param c the reflected constructor 967 * @return a method handle which can invoke the reflected constructor 968 * @throws IllegalAccessException if access checking fails 969 * or if the method's variable arity modifier bit 970 * is set and {@code asVarargsCollector} fails 971 * @throws NullPointerException if the argument is null 972 */ 973 @SuppressWarnings("rawtypes") // Will be Constructor<?> after JSR 292 MR 974 public MethodHandle unreflectConstructor(Constructor c) throws IllegalAccessException { 975 MemberName ctor = new MemberName(c); 976 assert(ctor.isConstructor()); 977 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 978 return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor); 979 } 980 981 /** 982 * Produces a method handle giving read access to a reflected field. 983 * The type of the method handle will have a return type of the field's 984 * value type. 985 * If the field is static, the method handle will take no arguments. 986 * Otherwise, its single argument will be the instance containing 987 * the field. 988 * If the field's {@code accessible} flag is not set, 989 * access checking is performed immediately on behalf of the lookup class. 990 * @param f the reflected field 991 * @return a method handle which can load values from the reflected field 992 * @throws IllegalAccessException if access checking fails 993 * @throws NullPointerException if the argument is null 994 */ 995 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 996 return unreflectField(f, false); 997 } 998 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 999 MemberName field = new MemberName(f, isSetter); 1000 assert(isSetter 1001 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 1002 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 1003 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 1004 return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field); 1005 } 1006 1007 /** 1008 * Produces a method handle giving write access to a reflected field. 1009 * The type of the method handle will have a void return type. 1010 * If the field is static, the method handle will take a single 1011 * argument, of the field's value type, the value to be stored. 1012 * Otherwise, the two arguments will be the instance containing 1013 * the field, and the value to be stored. 1014 * If the field's {@code accessible} flag is not set, 1015 * access checking is performed immediately on behalf of the lookup class. 1016 * @param f the reflected field 1017 * @return a method handle which can store values into the reflected field 1018 * @throws IllegalAccessException if access checking fails 1019 * @throws NullPointerException if the argument is null 1020 */ 1021 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 1022 return unreflectField(f, true); 1023 } 1024 1025 /// Helper methods, all package-private. 1026 1027 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1028 checkSymbolicClass(refc); // do this before attempting to resolve 1029 name.getClass(); type.getClass(); // NPE 1030 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1031 NoSuchFieldException.class); 1032 } 1033 1034 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1035 checkSymbolicClass(refc); // do this before attempting to resolve 1036 name.getClass(); type.getClass(); // NPE 1037 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1038 NoSuchMethodException.class); 1039 } 1040 1041 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 1042 Class<?> caller = lookupClassOrNull(); 1043 if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes)) 1044 throw new MemberName(refc).makeAccessException("symbolic reference class is not public", this); 1045 } 1046 1047 /** 1048 * Find my trustable caller class if m is a caller sensitive method. 1049 * If this lookup object has private access, then the caller class is the lookupClass. 1050 * Otherwise, it is the caller of the currently executing public API method (e.g., findVirtual). 1051 * This is the same caller class as is used by checkSecurityManager. 1052 */ 1053 Class<?> findBoundCallerClass(MemberName m, Class<?> callerAtEntryPoint) { 1054 Class<?> callerClass = null; 1055 if (MethodHandleNatives.isCallerSensitive(m)) { 1056 // Do not refactor this to a more "logical" place, since it is stack walk magic. 1057 // Note that this is the same expression as in Step 2 below in checkSecurityManager. 1058 callerClass = ((allowedModes & PRIVATE) != 0 1059 ? lookupClass // for strong access modes, no extra check 1060 : callerAtEntryPoint); 1061 } 1062 return callerClass; 1063 } 1064 1065 /** 1066 * Determine whether a security manager has an overridden 1067 * SecurityManager.checkMemberAccess method. 1068 */ 1069 private boolean isCheckMemberAccessOverridden(SecurityManager sm) { 1070 final Class<? extends SecurityManager> cls = sm.getClass(); 1071 if (cls == SecurityManager.class) return false; 1072 1073 try { 1074 return cls.getMethod("checkMemberAccess", Class.class, int.class). 1075 getDeclaringClass() != SecurityManager.class; 1076 } catch (NoSuchMethodException e) { 1077 throw new InternalError("should not reach here"); 1078 } 1079 } 1080 1081 /** 1082 * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 1083 * Determines a trustable caller class to compare with refc, the symbolic reference class. 1084 * If this lookup object has private access, then the caller class is the lookupClass. 1085 * Otherwise, it is the caller of the currently executing public API method (e.g., findVirtual). 1086 * This function performs stack walk magic: do not refactor it. 1087 */ 1088 void checkSecurityManager(Class<?> refc, MemberName m, Class<?> caller) { 1089 SecurityManager smgr = System.getSecurityManager(); 1090 if (smgr == null) return; 1091 if (allowedModes == TRUSTED) return; 1092 1093 final boolean overridden = isCheckMemberAccessOverridden(smgr); 1094 // Step 1: 1095 { 1096 // Default policy is to allow Member.PUBLIC; no need to check 1097 // permission if SecurityManager is the default implementation 1098 final int which = Member.PUBLIC; 1099 final Class<?> clazz = refc; 1100 if (overridden) { 1101 // Don't refactor; otherwise break the stack depth for 1102 // checkMemberAccess of subclasses of SecurityManager as specified. 1103 smgr.checkMemberAccess(clazz, which); 1104 } 1105 } 1106 1107 // Step 2: 1108 Class<?> callerClass = ((allowedModes & PRIVATE) != 0 1109 ? lookupClass // for strong access modes, no extra check 1110 : caller); 1111 if (!VerifyAccess.classLoaderIsAncestor(lookupClass, refc) || 1112 (callerClass != lookupClass && 1113 !VerifyAccess.classLoaderIsAncestor(callerClass, refc))) 1114 smgr.checkPackageAccess(VerifyAccess.getPackageName(refc)); 1115 1116 // Step 3: 1117 if (m.isPublic()) return; 1118 Class<?> defc = m.getDeclaringClass(); 1119 { 1120 // Inline SecurityManager.checkMemberAccess 1121 final int which = Member.DECLARED; 1122 final Class<?> clazz = defc; 1123 if (!overridden) { 1124 if (caller.getClassLoader() != clazz.getClassLoader()) { 1125 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 1126 } 1127 } else { 1128 // Don't refactor; otherwise break the stack depth for 1129 // checkMemberAccess of subclasses of SecurityManager as specified. 1130 smgr.checkMemberAccess(clazz, which); 1131 } 1132 } 1133 1134 // Step 4: 1135 if (defc != refc) 1136 smgr.checkPackageAccess(VerifyAccess.getPackageName(defc)); 1137 } 1138 1139 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1140 boolean wantStatic = (refKind == REF_invokeStatic); 1141 String message; 1142 if (m.isConstructor()) 1143 message = "expected a method, not a constructor"; 1144 else if (!m.isMethod()) 1145 message = "expected a method"; 1146 else if (wantStatic != m.isStatic()) 1147 message = wantStatic ? "expected a static method" : "expected a non-static method"; 1148 else 1149 { checkAccess(refKind, refc, m); return; } 1150 throw m.makeAccessException(message, this); 1151 } 1152 1153 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1154 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 1155 String message; 1156 if (wantStatic != m.isStatic()) 1157 message = wantStatic ? "expected a static field" : "expected a non-static field"; 1158 else 1159 { checkAccess(refKind, refc, m); return; } 1160 throw m.makeAccessException(message, this); 1161 } 1162 1163 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1164 assert(m.referenceKindIsConsistentWith(refKind) && 1165 MethodHandleNatives.refKindIsValid(refKind) && 1166 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 1167 int allowedModes = this.allowedModes; 1168 if (allowedModes == TRUSTED) return; 1169 int mods = m.getModifiers(); 1170 if (Modifier.isFinal(mods) && 1171 MethodHandleNatives.refKindIsSetter(refKind)) 1172 throw m.makeAccessException("unexpected set of a final field", this); 1173 if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0) 1174 return; // common case 1175 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 1176 if ((requestedModes & allowedModes) != 0) { 1177 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 1178 mods, lookupClass(), allowedModes)) 1179 return; 1180 } else { 1181 // Protected members can also be checked as if they were package-private. 1182 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 1183 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 1184 return; 1185 } 1186 throw m.makeAccessException(accessFailedMessage(refc, m), this); 1187 } 1188 1189 String accessFailedMessage(Class<?> refc, MemberName m) { 1190 Class<?> defc = m.getDeclaringClass(); 1191 int mods = m.getModifiers(); 1192 // check the class first: 1193 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 1194 (defc == refc || 1195 Modifier.isPublic(refc.getModifiers()))); 1196 if (!classOK && (allowedModes & PACKAGE) != 0) { 1197 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) && 1198 (defc == refc || 1199 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES))); 1200 } 1201 if (!classOK) 1202 return "class is not public"; 1203 if (Modifier.isPublic(mods)) 1204 return "access to public member failed"; // (how?) 1205 if (Modifier.isPrivate(mods)) 1206 return "member is private"; 1207 if (Modifier.isProtected(mods)) 1208 return "member is protected"; 1209 return "member is private to package"; 1210 } 1211 1212 private static final boolean ALLOW_NESTMATE_ACCESS = false; 1213 1214 private void checkSpecialCaller(Class<?> specialCaller) throws IllegalAccessException { 1215 int allowedModes = this.allowedModes; 1216 if (allowedModes == TRUSTED) return; 1217 if ((allowedModes & PRIVATE) == 0 1218 || (specialCaller != lookupClass() 1219 && !(ALLOW_NESTMATE_ACCESS && 1220 VerifyAccess.isSamePackageMember(specialCaller, lookupClass())))) 1221 throw new MemberName(specialCaller). 1222 makeAccessException("no private access for invokespecial", this); 1223 } 1224 1225 private boolean restrictProtectedReceiver(MemberName method) { 1226 // The accessing class only has the right to use a protected member 1227 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 1228 if (!method.isProtected() || method.isStatic() 1229 || allowedModes == TRUSTED 1230 || method.getDeclaringClass() == lookupClass() 1231 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()) 1232 || (ALLOW_NESTMATE_ACCESS && 1233 VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass()))) 1234 return false; 1235 return true; 1236 } 1237 private MethodHandle restrictReceiver(MemberName method, MethodHandle mh, Class<?> caller) throws IllegalAccessException { 1238 assert(!method.isStatic()); 1239 // receiver type of mh is too wide; narrow to caller 1240 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 1241 throw method.makeAccessException("caller class must be a subclass below the method", caller); 1242 } 1243 MethodType rawType = mh.type(); 1244 if (rawType.parameterType(0) == caller) return mh; 1245 MethodType narrowType = rawType.changeParameterType(0, caller); 1246 return mh.viewAsType(narrowType); 1247 } 1248 1249 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1250 return getDirectMethodCommon(refKind, refc, method, 1251 (refKind == REF_invokeSpecial || 1252 (MethodHandleNatives.refKindHasReceiver(refKind) && 1253 restrictProtectedReceiver(method))), callerClass); 1254 } 1255 private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1256 return getDirectMethodCommon(refKind, refc, method, false, callerClass); 1257 } 1258 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 1259 boolean doRestrict, Class<?> callerClass) throws IllegalAccessException { 1260 checkMethod(refKind, refc, method); 1261 if (method.isMethodHandleInvoke()) 1262 return fakeMethodHandleInvoke(method); 1263 1264 Class<?> refcAsSuper; 1265 if (refKind == REF_invokeSpecial && 1266 refc != lookupClass() && 1267 refc != (refcAsSuper = lookupClass().getSuperclass()) && 1268 refc.isAssignableFrom(lookupClass())) { 1269 assert(!method.getName().equals("<init>")); // not this code path 1270 // Per JVMS 6.5, desc. of invokespecial instruction: 1271 // If the method is in a superclass of the LC, 1272 // and if our original search was above LC.super, 1273 // repeat the search (symbolic lookup) from LC.super. 1274 // FIXME: MemberName.resolve should handle this instead. 1275 MemberName m2 = new MemberName(refcAsSuper, 1276 method.getName(), 1277 method.getMethodType(), 1278 REF_invokeSpecial); 1279 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); 1280 if (m2 == null) throw new InternalError(method.toString()); 1281 method = m2; 1282 refc = refcAsSuper; 1283 // redo basic checks 1284 checkMethod(refKind, refc, method); 1285 } 1286 1287 MethodHandle mh = DirectMethodHandle.make(refKind, refc, method); 1288 mh = maybeBindCaller(method, mh, callerClass); 1289 mh = mh.setVarargs(method); 1290 if (doRestrict) 1291 mh = restrictReceiver(method, mh, lookupClass()); 1292 return mh; 1293 } 1294 private MethodHandle fakeMethodHandleInvoke(MemberName method) { 1295 return throwException(method.getReturnType(), UnsupportedOperationException.class); 1296 } 1297 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, 1298 Class<?> callerClass) 1299 throws IllegalAccessException { 1300 if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 1301 return mh; 1302 Class<?> hostClass = lookupClass; 1303 if ((allowedModes & PRIVATE) == 0) // caller must use full-power lookup 1304 hostClass = callerClass; // callerClass came from a security manager style stack walk 1305 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); 1306 // Note: caller will apply varargs after this step happens. 1307 return cbmh; 1308 } 1309 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 1310 checkField(refKind, refc, field); 1311 MethodHandle mh = DirectMethodHandle.make(refc, field); 1312 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 1313 restrictProtectedReceiver(field)); 1314 if (doRestrict) 1315 mh = restrictReceiver(field, mh, lookupClass()); 1316 return mh; 1317 } 1318 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 1319 assert(ctor.isConstructor()); 1320 checkAccess(REF_newInvokeSpecial, refc, ctor); 1321 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 1322 return DirectMethodHandle.make(ctor).setVarargs(ctor); 1323 } 1324 1325 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 1326 */ 1327 /*non-public*/ 1328 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { 1329 MemberName resolved = null; 1330 if (type instanceof MemberName) { 1331 resolved = (MemberName) type; 1332 if (!resolved.isResolved()) throw new InternalError("unresolved MemberName"); 1333 assert(name == null || name.equals(resolved.getName())); 1334 } 1335 if (MethodHandleNatives.refKindIsField(refKind)) { 1336 MemberName field = (resolved != null) ? resolved 1337 : resolveOrFail(refKind, defc, name, (Class<?>) type); 1338 return getDirectField(refKind, defc, field); 1339 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 1340 MemberName method = (resolved != null) ? resolved 1341 : resolveOrFail(refKind, defc, name, (MethodType) type); 1342 return getDirectMethod(refKind, defc, method, lookupClass); 1343 } else if (refKind == REF_newInvokeSpecial) { 1344 assert(name == null || name.equals("<init>")); 1345 MemberName ctor = (resolved != null) ? resolved 1346 : resolveOrFail(REF_newInvokeSpecial, defc, name, (MethodType) type); 1347 return getDirectConstructor(defc, ctor); 1348 } 1349 // oops 1350 throw new ReflectiveOperationException("bad MethodHandle constant #"+refKind+" "+name+" : "+type); 1351 } 1352 } 1353 1354 /** 1355 * Produces a method handle giving read access to elements of an array. 1356 * The type of the method handle will have a return type of the array's 1357 * element type. Its first argument will be the array type, 1358 * and the second will be {@code int}. 1359 * @param arrayClass an array type 1360 * @return a method handle which can load values from the given array type 1361 * @throws NullPointerException if the argument is null 1362 * @throws IllegalArgumentException if arrayClass is not an array type 1363 */ 1364 public static 1365 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 1366 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false); 1367 } 1368 1369 /** 1370 * Produces a method handle giving write access to elements of an array. 1371 * The type of the method handle will have a void return type. 1372 * Its last argument will be the array's element type. 1373 * The first and second arguments will be the array type and int. 1374 * @return a method handle which can store values into the array type 1375 * @throws NullPointerException if the argument is null 1376 * @throws IllegalArgumentException if arrayClass is not an array type 1377 */ 1378 public static 1379 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 1380 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true); 1381 } 1382 1383 /// method handle invocation (reflective style) 1384 1385 /** 1386 * Produces a method handle which will invoke any method handle of the 1387 * given {@code type}, with a given number of trailing arguments replaced by 1388 * a single trailing {@code Object[]} array. 1389 * The resulting invoker will be a method handle with the following 1390 * arguments: 1391 * <ul> 1392 * <li>a single {@code MethodHandle} target 1393 * <li>zero or more leading values (counted by {@code leadingArgCount}) 1394 * <li>an {@code Object[]} array containing trailing arguments 1395 * </ul> 1396 * <p> 1397 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 1398 * the indicated {@code type}. 1399 * That is, if the target is exactly of the given {@code type}, it will behave 1400 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 1401 * is used to convert the target to the required {@code type}. 1402 * <p> 1403 * The type of the returned invoker will not be the given {@code type}, but rather 1404 * will have all parameters except the first {@code leadingArgCount} 1405 * replaced by a single array of type {@code Object[]}, which will be 1406 * the final parameter. 1407 * <p> 1408 * Before invoking its target, the invoker will spread the final array, apply 1409 * reference casts as necessary, and unbox and widen primitive arguments. 1410 * <p> 1411 * This method is equivalent to the following code (though it may be more efficient): 1412 * <p><blockquote><pre> 1413 MethodHandle invoker = MethodHandles.invoker(type); 1414 int spreadArgCount = type.parameterCount() - leadingArgCount; 1415 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 1416 return invoker; 1417 * </pre></blockquote> 1418 * <p> 1419 * This method throws no reflective or security exceptions. 1420 * @param type the desired target type 1421 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 1422 * @return a method handle suitable for invoking any method handle of the given type 1423 * @throws NullPointerException if {@code type} is null 1424 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 1425 * the range from 0 to {@code type.parameterCount()} inclusive 1426 */ 1427 static public 1428 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 1429 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 1430 throw new IllegalArgumentException("bad argument count "+leadingArgCount); 1431 return type.invokers().spreadInvoker(leadingArgCount); 1432 } 1433 1434 /** 1435 * Produces a special <em>invoker method handle</em> which can be used to 1436 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 1437 * The resulting invoker will have a type which is 1438 * exactly equal to the desired type, except that it will accept 1439 * an additional leading argument of type {@code MethodHandle}. 1440 * <p> 1441 * This method is equivalent to the following code (though it may be more efficient): 1442 * <p><blockquote><pre> 1443 publicLookup().findVirtual(MethodHandle.class, "invokeExact", type) 1444 * </pre></blockquote> 1445 * 1446 * <p style="font-size:smaller;"> 1447 * <em>Discussion:</em> 1448 * Invoker method handles can be useful when working with variable method handles 1449 * of unknown types. 1450 * For example, to emulate an {@code invokeExact} call to a variable method 1451 * handle {@code M}, extract its type {@code T}, 1452 * look up the invoker method {@code X} for {@code T}, 1453 * and call the invoker method, as {@code X.invoke(T, A...)}. 1454 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 1455 * is unknown.) 1456 * If spreading, collecting, or other argument transformations are required, 1457 * they can be applied once to the invoker {@code X} and reused on many {@code M} 1458 * method handle values, as long as they are compatible with the type of {@code X}. 1459 * <p> 1460 * <em>(Note: The invoker method is not available via the Core Reflection API. 1461 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 1462 * on the declared {@code invokeExact} or {@code invoke} method will raise an 1463 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 1464 * <p> 1465 * This method throws no reflective or security exceptions. 1466 * @param type the desired target type 1467 * @return a method handle suitable for invoking any method handle of the given type 1468 */ 1469 static public 1470 MethodHandle exactInvoker(MethodType type) { 1471 return type.invokers().exactInvoker(); 1472 } 1473 1474 /** 1475 * Produces a special <em>invoker method handle</em> which can be used to 1476 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 1477 * The resulting invoker will have a type which is 1478 * exactly equal to the desired type, except that it will accept 1479 * an additional leading argument of type {@code MethodHandle}. 1480 * <p> 1481 * Before invoking its target, if the target differs from the expected type, 1482 * the invoker will apply reference casts as 1483 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 1484 * Similarly, the return value will be converted as necessary. 1485 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 1486 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 1487 * <p> 1488 * A {@linkplain MethodType#genericMethodType general method type}, 1489 * mentions only {@code Object} arguments and return values. 1490 * An invoker for such a type is capable of calling any method handle 1491 * of the same arity as the general type. 1492 * <p> 1493 * This method is equivalent to the following code (though it may be more efficient): 1494 * <p><blockquote><pre> 1495 publicLookup().findVirtual(MethodHandle.class, "invoke", type) 1496 * </pre></blockquote> 1497 * <p> 1498 * This method throws no reflective or security exceptions. 1499 * @param type the desired target type 1500 * @return a method handle suitable for invoking any method handle convertible to the given type 1501 */ 1502 static public 1503 MethodHandle invoker(MethodType type) { 1504 return type.invokers().generalInvoker(); 1505 } 1506 1507 static /*non-public*/ 1508 MethodHandle basicInvoker(MethodType type) { 1509 return type.form().basicInvoker(); 1510 } 1511 1512 /// method handle modification (creation from other method handles) 1513 1514 /** 1515 * Produces a method handle which adapts the type of the 1516 * given method handle to a new type by pairwise argument and return type conversion. 1517 * The original type and new type must have the same number of arguments. 1518 * The resulting method handle is guaranteed to report a type 1519 * which is equal to the desired new type. 1520 * <p> 1521 * If the original type and new type are equal, returns target. 1522 * <p> 1523 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 1524 * and some additional conversions are also applied if those conversions fail. 1525 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 1526 * if possible, before or instead of any conversions done by {@code asType}: 1527 * <ul> 1528 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 1529 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 1530 * (This treatment of interfaces follows the usage of the bytecode verifier.) 1531 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 1532 * the boolean is converted to a byte value, 1 for true, 0 for false. 1533 * (This treatment follows the usage of the bytecode verifier.) 1534 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 1535 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 1536 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 1537 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 1538 * then a Java casting conversion (JLS 5.5) is applied. 1539 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 1540 * widening and/or narrowing.) 1541 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 1542 * conversion will be applied at runtime, possibly followed 1543 * by a Java casting conversion (JLS 5.5) on the primitive value, 1544 * possibly followed by a conversion from byte to boolean by testing 1545 * the low-order bit. 1546 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 1547 * and if the reference is null at runtime, a zero value is introduced. 1548 * </ul> 1549 * @param target the method handle to invoke after arguments are retyped 1550 * @param newType the expected type of the new method handle 1551 * @return a method handle which delegates to the target after performing 1552 * any necessary argument conversions, and arranges for any 1553 * necessary return value conversions 1554 * @throws NullPointerException if either argument is null 1555 * @throws WrongMethodTypeException if the conversion cannot be made 1556 * @see MethodHandle#asType 1557 */ 1558 public static 1559 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 1560 if (!target.type().isCastableTo(newType)) { 1561 throw new WrongMethodTypeException("cannot explicitly cast "+target+" to "+newType); 1562 } 1563 return MethodHandleImpl.makePairwiseConvert(target, newType, 2); 1564 } 1565 1566 /** 1567 * Produces a method handle which adapts the calling sequence of the 1568 * given method handle to a new type, by reordering the arguments. 1569 * The resulting method handle is guaranteed to report a type 1570 * which is equal to the desired new type. 1571 * <p> 1572 * The given array controls the reordering. 1573 * Call {@code #I} the number of incoming parameters (the value 1574 * {@code newType.parameterCount()}, and call {@code #O} the number 1575 * of outgoing parameters (the value {@code target.type().parameterCount()}). 1576 * Then the length of the reordering array must be {@code #O}, 1577 * and each element must be a non-negative number less than {@code #I}. 1578 * For every {@code N} less than {@code #O}, the {@code N}-th 1579 * outgoing argument will be taken from the {@code I}-th incoming 1580 * argument, where {@code I} is {@code reorder[N]}. 1581 * <p> 1582 * No argument or return value conversions are applied. 1583 * The type of each incoming argument, as determined by {@code newType}, 1584 * must be identical to the type of the corresponding outgoing parameter 1585 * or parameters in the target method handle. 1586 * The return type of {@code newType} must be identical to the return 1587 * type of the original target. 1588 * <p> 1589 * The reordering array need not specify an actual permutation. 1590 * An incoming argument will be duplicated if its index appears 1591 * more than once in the array, and an incoming argument will be dropped 1592 * if its index does not appear in the array. 1593 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 1594 * incoming arguments which are not mentioned in the reordering array 1595 * are may be any type, as determined only by {@code newType}. 1596 * <blockquote><pre>{@code 1597 import static java.lang.invoke.MethodHandles.*; 1598 import static java.lang.invoke.MethodType.*; 1599 ... 1600 MethodType intfn1 = methodType(int.class, int.class); 1601 MethodType intfn2 = methodType(int.class, int.class, int.class); 1602 MethodHandle sub = ... {int x, int y => x-y} ...; 1603 assert(sub.type().equals(intfn2)); 1604 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 1605 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 1606 assert((int)rsub.invokeExact(1, 100) == 99); 1607 MethodHandle add = ... {int x, int y => x+y} ...; 1608 assert(add.type().equals(intfn2)); 1609 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 1610 assert(twice.type().equals(intfn1)); 1611 assert((int)twice.invokeExact(21) == 42); 1612 * }</pre></blockquote> 1613 * @param target the method handle to invoke after arguments are reordered 1614 * @param newType the expected type of the new method handle 1615 * @param reorder an index array which controls the reordering 1616 * @return a method handle which delegates to the target after it 1617 * drops unused arguments and moves and/or duplicates the other arguments 1618 * @throws NullPointerException if any argument is null 1619 * @throws IllegalArgumentException if the index array length is not equal to 1620 * the arity of the target, or if any index array element 1621 * not a valid index for a parameter of {@code newType}, 1622 * or if two corresponding parameter types in 1623 * {@code target.type()} and {@code newType} are not identical, 1624 */ 1625 public static 1626 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 1627 checkReorder(reorder, newType, target.type()); 1628 return target.permuteArguments(newType, reorder); 1629 } 1630 1631 private static void checkReorder(int[] reorder, MethodType newType, MethodType oldType) { 1632 if (newType.returnType() != oldType.returnType()) 1633 throw newIllegalArgumentException("return types do not match", 1634 oldType, newType); 1635 if (reorder.length == oldType.parameterCount()) { 1636 int limit = newType.parameterCount(); 1637 boolean bad = false; 1638 for (int j = 0; j < reorder.length; j++) { 1639 int i = reorder[j]; 1640 if (i < 0 || i >= limit) { 1641 bad = true; break; 1642 } 1643 Class<?> src = newType.parameterType(i); 1644 Class<?> dst = oldType.parameterType(j); 1645 if (src != dst) 1646 throw newIllegalArgumentException("parameter types do not match after reorder", 1647 oldType, newType); 1648 } 1649 if (!bad) return; 1650 } 1651 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 1652 } 1653 1654 /** 1655 * Produces a method handle of the requested return type which returns the given 1656 * constant value every time it is invoked. 1657 * <p> 1658 * Before the method handle is returned, the passed-in value is converted to the requested type. 1659 * If the requested type is primitive, widening primitive conversions are attempted, 1660 * else reference conversions are attempted. 1661 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 1662 * @param type the return type of the desired method handle 1663 * @param value the value to return 1664 * @return a method handle of the given return type and no arguments, which always returns the given value 1665 * @throws NullPointerException if the {@code type} argument is null 1666 * @throws ClassCastException if the value cannot be converted to the required return type 1667 * @throws IllegalArgumentException if the given type is {@code void.class} 1668 */ 1669 public static 1670 MethodHandle constant(Class<?> type, Object value) { 1671 if (type.isPrimitive()) { 1672 if (type == void.class) 1673 throw newIllegalArgumentException("void type"); 1674 Wrapper w = Wrapper.forPrimitiveType(type); 1675 return insertArguments(identity(type), 0, w.convert(value, type)); 1676 } else { 1677 return identity(type).bindTo(type.cast(value)); 1678 } 1679 } 1680 1681 /** 1682 * Produces a method handle which returns its sole argument when invoked. 1683 * @param type the type of the sole parameter and return value of the desired method handle 1684 * @return a unary method handle which accepts and returns the given type 1685 * @throws NullPointerException if the argument is null 1686 * @throws IllegalArgumentException if the given type is {@code void.class} 1687 */ 1688 public static 1689 MethodHandle identity(Class<?> type) { 1690 if (type == void.class) 1691 throw newIllegalArgumentException("void type"); 1692 else if (type == Object.class) 1693 return ValueConversions.identity(); 1694 else if (type.isPrimitive()) 1695 return ValueConversions.identity(Wrapper.forPrimitiveType(type)); 1696 else 1697 return MethodHandleImpl.makeReferenceIdentity(type); 1698 } 1699 1700 /** 1701 * Provides a target method handle with one or more <em>bound arguments</em> 1702 * in advance of the method handle's invocation. 1703 * The formal parameters to the target corresponding to the bound 1704 * arguments are called <em>bound parameters</em>. 1705 * Returns a new method handle which saves away the bound arguments. 1706 * When it is invoked, it receives arguments for any non-bound parameters, 1707 * binds the saved arguments to their corresponding parameters, 1708 * and calls the original target. 1709 * <p> 1710 * The type of the new method handle will drop the types for the bound 1711 * parameters from the original target type, since the new method handle 1712 * will no longer require those arguments to be supplied by its callers. 1713 * <p> 1714 * Each given argument object must match the corresponding bound parameter type. 1715 * If a bound parameter type is a primitive, the argument object 1716 * must be a wrapper, and will be unboxed to produce the primitive value. 1717 * <p> 1718 * The {@code pos} argument selects which parameters are to be bound. 1719 * It may range between zero and <i>N-L</i> (inclusively), 1720 * where <i>N</i> is the arity of the target method handle 1721 * and <i>L</i> is the length of the values array. 1722 * @param target the method handle to invoke after the argument is inserted 1723 * @param pos where to insert the argument (zero for the first) 1724 * @param values the series of arguments to insert 1725 * @return a method handle which inserts an additional argument, 1726 * before calling the original method handle 1727 * @throws NullPointerException if the target or the {@code values} array is null 1728 * @see MethodHandle#bindTo 1729 */ 1730 public static 1731 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 1732 int insCount = values.length; 1733 MethodType oldType = target.type(); 1734 int outargs = oldType.parameterCount(); 1735 int inargs = outargs - insCount; 1736 if (inargs < 0) 1737 throw newIllegalArgumentException("too many values to insert"); 1738 if (pos < 0 || pos > inargs) 1739 throw newIllegalArgumentException("no argument type to append"); 1740 MethodHandle result = target; 1741 for (int i = 0; i < insCount; i++) { 1742 Object value = values[i]; 1743 Class<?> ptype = oldType.parameterType(pos+i); 1744 if (ptype.isPrimitive()) { 1745 char btype = 'I'; 1746 Wrapper w = Wrapper.forPrimitiveType(ptype); 1747 switch (w) { 1748 case LONG: btype = 'J'; break; 1749 case FLOAT: btype = 'F'; break; 1750 case DOUBLE: btype = 'D'; break; 1751 } 1752 // perform unboxing and/or primitive conversion 1753 value = w.convert(value, ptype); 1754 result = result.bindArgument(pos, btype, value); 1755 continue; 1756 } 1757 value = ptype.cast(value); // throw CCE if needed 1758 if (pos == 0) { 1759 result = result.bindReceiver(value); 1760 } else { 1761 result = result.bindArgument(pos, 'L', value); 1762 } 1763 } 1764 return result; 1765 } 1766 1767 /** 1768 * Produces a method handle which will discard some dummy arguments 1769 * before calling some other specified <i>target</i> method handle. 1770 * The type of the new method handle will be the same as the target's type, 1771 * except it will also include the dummy argument types, 1772 * at some given position. 1773 * <p> 1774 * The {@code pos} argument may range between zero and <i>N</i>, 1775 * where <i>N</i> is the arity of the target. 1776 * If {@code pos} is zero, the dummy arguments will precede 1777 * the target's real arguments; if {@code pos} is <i>N</i> 1778 * they will come after. 1779 * <p> 1780 * <b>Example:</b> 1781 * <p><blockquote><pre> 1782 import static java.lang.invoke.MethodHandles.*; 1783 import static java.lang.invoke.MethodType.*; 1784 ... 1785 MethodHandle cat = lookup().findVirtual(String.class, 1786 "concat", methodType(String.class, String.class)); 1787 assertEquals("xy", (String) cat.invokeExact("x", "y")); 1788 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 1789 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 1790 assertEquals(bigType, d0.type()); 1791 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 1792 * </pre></blockquote> 1793 * <p> 1794 * This method is also equivalent to the following code: 1795 * <p><blockquote><pre> 1796 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}(target, pos, valueTypes.toArray(new Class[0])) 1797 * </pre></blockquote> 1798 * @param target the method handle to invoke after the arguments are dropped 1799 * @param valueTypes the type(s) of the argument(s) to drop 1800 * @param pos position of first argument to drop (zero for the leftmost) 1801 * @return a method handle which drops arguments of the given types, 1802 * before calling the original method handle 1803 * @throws NullPointerException if the target is null, 1804 * or if the {@code valueTypes} list or any of its elements is null 1805 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 1806 * or if {@code pos} is negative or greater than the arity of the target, 1807 * or if the new method handle's type would have too many parameters 1808 */ 1809 public static 1810 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 1811 MethodType oldType = target.type(); // get NPE 1812 int dropped = valueTypes.size(); 1813 MethodType.checkSlotCount(dropped); 1814 if (dropped == 0) return target; 1815 int outargs = oldType.parameterCount(); 1816 int inargs = outargs + dropped; 1817 if (pos < 0 || pos >= inargs) 1818 throw newIllegalArgumentException("no argument type to remove"); 1819 ArrayList<Class<?>> ptypes = new ArrayList<>(oldType.parameterList()); 1820 ptypes.addAll(pos, valueTypes); 1821 MethodType newType = MethodType.methodType(oldType.returnType(), ptypes); 1822 return target.dropArguments(newType, pos, dropped); 1823 } 1824 1825 /** 1826 * Produces a method handle which will discard some dummy arguments 1827 * before calling some other specified <i>target</i> method handle. 1828 * The type of the new method handle will be the same as the target's type, 1829 * except it will also include the dummy argument types, 1830 * at some given position. 1831 * <p> 1832 * The {@code pos} argument may range between zero and <i>N</i>, 1833 * where <i>N</i> is the arity of the target. 1834 * If {@code pos} is zero, the dummy arguments will precede 1835 * the target's real arguments; if {@code pos} is <i>N</i> 1836 * they will come after. 1837 * <p> 1838 * <b>Example:</b> 1839 * <p><blockquote><pre> 1840 import static java.lang.invoke.MethodHandles.*; 1841 import static java.lang.invoke.MethodType.*; 1842 ... 1843 MethodHandle cat = lookup().findVirtual(String.class, 1844 "concat", methodType(String.class, String.class)); 1845 assertEquals("xy", (String) cat.invokeExact("x", "y")); 1846 MethodHandle d0 = dropArguments(cat, 0, String.class); 1847 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 1848 MethodHandle d1 = dropArguments(cat, 1, String.class); 1849 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 1850 MethodHandle d2 = dropArguments(cat, 2, String.class); 1851 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 1852 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 1853 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 1854 * </pre></blockquote> 1855 * <p> 1856 * This method is also equivalent to the following code: 1857 * <p><blockquote><pre> 1858 * {@link #dropArguments(MethodHandle,int,List) dropArguments}(target, pos, Arrays.asList(valueTypes)) 1859 * </pre></blockquote> 1860 * @param target the method handle to invoke after the arguments are dropped 1861 * @param valueTypes the type(s) of the argument(s) to drop 1862 * @param pos position of first argument to drop (zero for the leftmost) 1863 * @return a method handle which drops arguments of the given types, 1864 * before calling the original method handle 1865 * @throws NullPointerException if the target is null, 1866 * or if the {@code valueTypes} array or any of its elements is null 1867 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 1868 * or if {@code pos} is negative or greater than the arity of the target, 1869 * or if the new method handle's type would have too many parameters 1870 */ 1871 public static 1872 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 1873 return dropArguments(target, pos, Arrays.asList(valueTypes)); 1874 } 1875 1876 /** 1877 * Adapts a target method handle by pre-processing 1878 * one or more of its arguments, each with its own unary filter function, 1879 * and then calling the target with each pre-processed argument 1880 * replaced by the result of its corresponding filter function. 1881 * <p> 1882 * The pre-processing is performed by one or more method handles, 1883 * specified in the elements of the {@code filters} array. 1884 * The first element of the filter array corresponds to the {@code pos} 1885 * argument of the target, and so on in sequence. 1886 * <p> 1887 * Null arguments in the array are treated as identity functions, 1888 * and the corresponding arguments left unchanged. 1889 * (If there are no non-null elements in the array, the original target is returned.) 1890 * Each filter is applied to the corresponding argument of the adapter. 1891 * <p> 1892 * If a filter {@code F} applies to the {@code N}th argument of 1893 * the target, then {@code F} must be a method handle which 1894 * takes exactly one argument. The type of {@code F}'s sole argument 1895 * replaces the corresponding argument type of the target 1896 * in the resulting adapted method handle. 1897 * The return type of {@code F} must be identical to the corresponding 1898 * parameter type of the target. 1899 * <p> 1900 * It is an error if there are elements of {@code filters} 1901 * (null or not) 1902 * which do not correspond to argument positions in the target. 1903 * <b>Example:</b> 1904 * <p><blockquote><pre> 1905 import static java.lang.invoke.MethodHandles.*; 1906 import static java.lang.invoke.MethodType.*; 1907 ... 1908 MethodHandle cat = lookup().findVirtual(String.class, 1909 "concat", methodType(String.class, String.class)); 1910 MethodHandle upcase = lookup().findVirtual(String.class, 1911 "toUpperCase", methodType(String.class)); 1912 assertEquals("xy", (String) cat.invokeExact("x", "y")); 1913 MethodHandle f0 = filterArguments(cat, 0, upcase); 1914 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 1915 MethodHandle f1 = filterArguments(cat, 1, upcase); 1916 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 1917 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 1918 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 1919 * </pre></blockquote> 1920 * <p> Here is pseudocode for the resulting adapter: 1921 * <blockquote><pre> 1922 * V target(P... p, A[i]... a[i], B... b); 1923 * A[i] filter[i](V[i]); 1924 * T adapter(P... p, V[i]... v[i], B... b) { 1925 * return target(p..., f[i](v[i])..., b...); 1926 * } 1927 * </pre></blockquote> 1928 * 1929 * @param target the method handle to invoke after arguments are filtered 1930 * @param pos the position of the first argument to filter 1931 * @param filters method handles to call initially on filtered arguments 1932 * @return method handle which incorporates the specified argument filtering logic 1933 * @throws NullPointerException if the target is null 1934 * or if the {@code filters} array is null 1935 * @throws IllegalArgumentException if a non-null element of {@code filters} 1936 * does not match a corresponding argument type of target as described above, 1937 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()} 1938 */ 1939 public static 1940 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 1941 MethodType targetType = target.type(); 1942 MethodHandle adapter = target; 1943 MethodType adapterType = null; 1944 assert((adapterType = targetType) != null); 1945 int maxPos = targetType.parameterCount(); 1946 if (pos + filters.length > maxPos) 1947 throw newIllegalArgumentException("too many filters"); 1948 int curPos = pos-1; // pre-incremented 1949 for (MethodHandle filter : filters) { 1950 curPos += 1; 1951 if (filter == null) continue; // ignore null elements of filters 1952 adapter = filterArgument(adapter, curPos, filter); 1953 assert((adapterType = adapterType.changeParameterType(curPos, filter.type().parameterType(0))) != null); 1954 } 1955 assert(adapterType.equals(adapter.type())); 1956 return adapter; 1957 } 1958 1959 /*non-public*/ static 1960 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 1961 MethodType targetType = target.type(); 1962 MethodType filterType = filter.type(); 1963 if (filterType.parameterCount() != 1 1964 || filterType.returnType() != targetType.parameterType(pos)) 1965 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 1966 return MethodHandleImpl.makeCollectArguments(target, filter, pos, false); 1967 } 1968 1969 // FIXME: Make this public in M1. 1970 /*non-public*/ static 1971 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle collector) { 1972 MethodType targetType = target.type(); 1973 MethodType filterType = collector.type(); 1974 if (filterType.returnType() != void.class && 1975 filterType.returnType() != targetType.parameterType(pos)) 1976 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 1977 return MethodHandleImpl.makeCollectArguments(target, collector, pos, false); 1978 } 1979 1980 /** 1981 * Adapts a target method handle by post-processing 1982 * its return value (if any) with a filter (another method handle). 1983 * The result of the filter is returned from the adapter. 1984 * <p> 1985 * If the target returns a value, the filter must accept that value as 1986 * its only argument. 1987 * If the target returns void, the filter must accept no arguments. 1988 * <p> 1989 * The return type of the filter 1990 * replaces the return type of the target 1991 * in the resulting adapted method handle. 1992 * The argument type of the filter (if any) must be identical to the 1993 * return type of the target. 1994 * <b>Example:</b> 1995 * <p><blockquote><pre> 1996 import static java.lang.invoke.MethodHandles.*; 1997 import static java.lang.invoke.MethodType.*; 1998 ... 1999 MethodHandle cat = lookup().findVirtual(String.class, 2000 "concat", methodType(String.class, String.class)); 2001 MethodHandle length = lookup().findVirtual(String.class, 2002 "length", methodType(int.class)); 2003 System.out.println((String) cat.invokeExact("x", "y")); // xy 2004 MethodHandle f0 = filterReturnValue(cat, length); 2005 System.out.println((int) f0.invokeExact("x", "y")); // 2 2006 * </pre></blockquote> 2007 * <p> Here is pseudocode for the resulting adapter: 2008 * <blockquote><pre> 2009 * V target(A...); 2010 * T filter(V); 2011 * T adapter(A... a) { 2012 * V v = target(a...); 2013 * return filter(v); 2014 * } 2015 * // and if the target has a void return: 2016 * void target2(A...); 2017 * T filter2(); 2018 * T adapter2(A... a) { 2019 * target2(a...); 2020 * return filter2(); 2021 * } 2022 * // and if the filter has a void return: 2023 * V target3(A...); 2024 * void filter3(V); 2025 * void adapter3(A... a) { 2026 * V v = target3(a...); 2027 * filter3(v); 2028 * } 2029 * </pre></blockquote> 2030 * @param target the method handle to invoke before filtering the return value 2031 * @param filter method handle to call on the return value 2032 * @return method handle which incorporates the specified return value filtering logic 2033 * @throws NullPointerException if either argument is null 2034 * @throws IllegalArgumentException if the argument list of {@code filter} 2035 * does not match the return type of target as described above 2036 */ 2037 public static 2038 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 2039 MethodType targetType = target.type(); 2040 MethodType filterType = filter.type(); 2041 Class<?> rtype = targetType.returnType(); 2042 int filterValues = filterType.parameterCount(); 2043 if (filterValues == 0 2044 ? (rtype != void.class) 2045 : (rtype != filterType.parameterType(0))) 2046 throw newIllegalArgumentException("target and filter types do not match", target, filter); 2047 // result = fold( lambda(retval, arg...) { filter(retval) }, 2048 // lambda( arg...) { target(arg...) } ) 2049 return MethodHandleImpl.makeCollectArguments(filter, target, 0, false); 2050 } 2051 2052 /** 2053 * Adapts a target method handle by pre-processing 2054 * some of its arguments, and then calling the target with 2055 * the result of the pre-processing, inserted into the original 2056 * sequence of arguments. 2057 * <p> 2058 * The pre-processing is performed by {@code combiner}, a second method handle. 2059 * Of the arguments passed to the adapter, the first {@code N} arguments 2060 * are copied to the combiner, which is then called. 2061 * (Here, {@code N} is defined as the parameter count of the combiner.) 2062 * After this, control passes to the target, with any result 2063 * from the combiner inserted before the original {@code N} incoming 2064 * arguments. 2065 * <p> 2066 * If the combiner returns a value, the first parameter type of the target 2067 * must be identical with the return type of the combiner, and the next 2068 * {@code N} parameter types of the target must exactly match the parameters 2069 * of the combiner. 2070 * <p> 2071 * If the combiner has a void return, no result will be inserted, 2072 * and the first {@code N} parameter types of the target 2073 * must exactly match the parameters of the combiner. 2074 * <p> 2075 * The resulting adapter is the same type as the target, except that the 2076 * first parameter type is dropped, 2077 * if it corresponds to the result of the combiner. 2078 * <p> 2079 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 2080 * that either the combiner or the target does not wish to receive. 2081 * If some of the incoming arguments are destined only for the combiner, 2082 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 2083 * arguments will not need to be live on the stack on entry to the 2084 * target.) 2085 * <b>Example:</b> 2086 * <p><blockquote><pre> 2087 import static java.lang.invoke.MethodHandles.*; 2088 import static java.lang.invoke.MethodType.*; 2089 ... 2090 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 2091 "println", methodType(void.class, String.class)) 2092 .bindTo(System.out); 2093 MethodHandle cat = lookup().findVirtual(String.class, 2094 "concat", methodType(String.class, String.class)); 2095 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 2096 MethodHandle catTrace = foldArguments(cat, trace); 2097 // also prints "boo": 2098 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 2099 * </pre></blockquote> 2100 * <p> Here is pseudocode for the resulting adapter: 2101 * <blockquote><pre> 2102 * // there are N arguments in A... 2103 * T target(V, A[N]..., B...); 2104 * V combiner(A...); 2105 * T adapter(A... a, B... b) { 2106 * V v = combiner(a...); 2107 * return target(v, a..., b...); 2108 * } 2109 * // and if the combiner has a void return: 2110 * T target2(A[N]..., B...); 2111 * void combiner2(A...); 2112 * T adapter2(A... a, B... b) { 2113 * combiner2(a...); 2114 * return target2(a..., b...); 2115 * } 2116 * </pre></blockquote> 2117 * @param target the method handle to invoke after arguments are combined 2118 * @param combiner method handle to call initially on the incoming arguments 2119 * @return method handle which incorporates the specified argument folding logic 2120 * @throws NullPointerException if either argument is null 2121 * @throws IllegalArgumentException if {@code combiner}'s return type 2122 * is non-void and not the same as the first argument type of 2123 * the target, or if the initial {@code N} argument types 2124 * of the target 2125 * (skipping one matching the {@code combiner}'s return type) 2126 * are not identical with the argument types of {@code combiner} 2127 */ 2128 public static 2129 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 2130 int pos = 0; 2131 MethodType targetType = target.type(); 2132 MethodType combinerType = combiner.type(); 2133 int foldPos = pos; 2134 int foldArgs = combinerType.parameterCount(); 2135 int foldVals = combinerType.returnType() == void.class ? 0 : 1; 2136 int afterInsertPos = foldPos + foldVals; 2137 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 2138 if (ok && !(combinerType.parameterList() 2139 .equals(targetType.parameterList().subList(afterInsertPos, 2140 afterInsertPos + foldArgs)))) 2141 ok = false; 2142 if (ok && foldVals != 0 && !combinerType.returnType().equals(targetType.parameterType(0))) 2143 ok = false; 2144 if (!ok) 2145 throw misMatchedTypes("target and combiner types", targetType, combinerType); 2146 MethodType newType = targetType.dropParameterTypes(foldPos, afterInsertPos); 2147 return MethodHandleImpl.makeCollectArguments(target, combiner, foldPos, true); 2148 } 2149 2150 /** 2151 * Makes a method handle which adapts a target method handle, 2152 * by guarding it with a test, a boolean-valued method handle. 2153 * If the guard fails, a fallback handle is called instead. 2154 * All three method handles must have the same corresponding 2155 * argument and return types, except that the return type 2156 * of the test must be boolean, and the test is allowed 2157 * to have fewer arguments than the other two method handles. 2158 * <p> Here is pseudocode for the resulting adapter: 2159 * <blockquote><pre> 2160 * boolean test(A...); 2161 * T target(A...,B...); 2162 * T fallback(A...,B...); 2163 * T adapter(A... a,B... b) { 2164 * if (test(a...)) 2165 * return target(a..., b...); 2166 * else 2167 * return fallback(a..., b...); 2168 * } 2169 * </pre></blockquote> 2170 * Note that the test arguments ({@code a...} in the pseudocode) cannot 2171 * be modified by execution of the test, and so are passed unchanged 2172 * from the caller to the target or fallback as appropriate. 2173 * @param test method handle used for test, must return boolean 2174 * @param target method handle to call if test passes 2175 * @param fallback method handle to call if test fails 2176 * @return method handle which incorporates the specified if/then/else logic 2177 * @throws NullPointerException if any argument is null 2178 * @throws IllegalArgumentException if {@code test} does not return boolean, 2179 * or if all three method types do not match (with the return 2180 * type of {@code test} changed to match that of the target). 2181 */ 2182 public static 2183 MethodHandle guardWithTest(MethodHandle test, 2184 MethodHandle target, 2185 MethodHandle fallback) { 2186 MethodType gtype = test.type(); 2187 MethodType ttype = target.type(); 2188 MethodType ftype = fallback.type(); 2189 if (!ttype.equals(ftype)) 2190 throw misMatchedTypes("target and fallback types", ttype, ftype); 2191 if (gtype.returnType() != boolean.class) 2192 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 2193 List<Class<?>> targs = ttype.parameterList(); 2194 List<Class<?>> gargs = gtype.parameterList(); 2195 if (!targs.equals(gargs)) { 2196 int gpc = gargs.size(), tpc = targs.size(); 2197 if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs)) 2198 throw misMatchedTypes("target and test types", ttype, gtype); 2199 test = dropArguments(test, gpc, targs.subList(gpc, tpc)); 2200 gtype = test.type(); 2201 } 2202 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 2203 } 2204 2205 static RuntimeException misMatchedTypes(String what, MethodType t1, MethodType t2) { 2206 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 2207 } 2208 2209 /** 2210 * Makes a method handle which adapts a target method handle, 2211 * by running it inside an exception handler. 2212 * If the target returns normally, the adapter returns that value. 2213 * If an exception matching the specified type is thrown, the fallback 2214 * handle is called instead on the exception, plus the original arguments. 2215 * <p> 2216 * The target and handler must have the same corresponding 2217 * argument and return types, except that handler may omit trailing arguments 2218 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 2219 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 2220 * <p> Here is pseudocode for the resulting adapter: 2221 * <blockquote><pre> 2222 * T target(A..., B...); 2223 * T handler(ExType, A...); 2224 * T adapter(A... a, B... b) { 2225 * try { 2226 * return target(a..., b...); 2227 * } catch (ExType ex) { 2228 * return handler(ex, a...); 2229 * } 2230 * } 2231 * </pre></blockquote> 2232 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 2233 * be modified by execution of the target, and so are passed unchanged 2234 * from the caller to the handler, if the handler is invoked. 2235 * <p> 2236 * The target and handler must return the same type, even if the handler 2237 * always throws. (This might happen, for instance, because the handler 2238 * is simulating a {@code finally} clause). 2239 * To create such a throwing handler, compose the handler creation logic 2240 * with {@link #throwException throwException}, 2241 * in order to create a method handle of the correct return type. 2242 * @param target method handle to call 2243 * @param exType the type of exception which the handler will catch 2244 * @param handler method handle to call if a matching exception is thrown 2245 * @return method handle which incorporates the specified try/catch logic 2246 * @throws NullPointerException if any argument is null 2247 * @throws IllegalArgumentException if {@code handler} does not accept 2248 * the given exception type, or if the method handle types do 2249 * not match in their return types and their 2250 * corresponding parameters 2251 */ 2252 public static 2253 MethodHandle catchException(MethodHandle target, 2254 Class<? extends Throwable> exType, 2255 MethodHandle handler) { 2256 MethodType ttype = target.type(); 2257 MethodType htype = handler.type(); 2258 if (htype.parameterCount() < 1 || 2259 !htype.parameterType(0).isAssignableFrom(exType)) 2260 throw newIllegalArgumentException("handler does not accept exception type "+exType); 2261 if (htype.returnType() != ttype.returnType()) 2262 throw misMatchedTypes("target and handler return types", ttype, htype); 2263 List<Class<?>> targs = ttype.parameterList(); 2264 List<Class<?>> hargs = htype.parameterList(); 2265 hargs = hargs.subList(1, hargs.size()); // omit leading parameter from handler 2266 if (!targs.equals(hargs)) { 2267 int hpc = hargs.size(), tpc = targs.size(); 2268 if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs)) 2269 throw misMatchedTypes("target and handler types", ttype, htype); 2270 handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc)); 2271 htype = handler.type(); 2272 } 2273 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 2274 } 2275 2276 /** 2277 * Produces a method handle which will throw exceptions of the given {@code exType}. 2278 * The method handle will accept a single argument of {@code exType}, 2279 * and immediately throw it as an exception. 2280 * The method type will nominally specify a return of {@code returnType}. 2281 * The return type may be anything convenient: It doesn't matter to the 2282 * method handle's behavior, since it will never return normally. 2283 * @return method handle which can throw the given exceptions 2284 * @throws NullPointerException if either argument is null 2285 */ 2286 public static 2287 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 2288 if (!Throwable.class.isAssignableFrom(exType)) 2289 throw new ClassCastException(exType.getName()); 2290 return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType)); 2291 } 2292 }