1 /* 2 * Copyright (c) 2008, 2016, 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 jdk.internal.org.objectweb.asm.ClassWriter; 29 import jdk.internal.org.objectweb.asm.Opcodes; 30 import jdk.internal.reflect.CallerSensitive; 31 import jdk.internal.reflect.Reflection; 32 import sun.invoke.util.ValueConversions; 33 import sun.invoke.util.VerifyAccess; 34 import sun.invoke.util.Wrapper; 35 import sun.reflect.misc.ReflectUtil; 36 import sun.security.util.SecurityConstants; 37 38 import java.lang.invoke.LambdaForm.BasicType; 39 import java.lang.reflect.Constructor; 40 import java.lang.reflect.Field; 41 import java.lang.reflect.Member; 42 import java.lang.reflect.Method; 43 import java.lang.reflect.Modifier; 44 import java.lang.reflect.ReflectPermission; 45 import java.nio.ByteOrder; 46 import java.security.AccessController; 47 import java.security.PrivilegedAction; 48 import java.util.ArrayList; 49 import java.util.Arrays; 50 import java.util.BitSet; 51 import java.util.Iterator; 52 import java.util.List; 53 import java.util.Objects; 54 import java.util.concurrent.ConcurrentHashMap; 55 import java.util.stream.Collectors; 56 import java.util.stream.Stream; 57 58 import static java.lang.invoke.MethodHandleImpl.Intrinsic; 59 import static java.lang.invoke.MethodHandleNatives.Constants.*; 60 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 61 import static java.lang.invoke.MethodType.methodType; 62 63 /** 64 * This class consists exclusively of static methods that operate on or return 65 * method handles. They fall into several categories: 66 * <ul> 67 * <li>Lookup methods which help create method handles for methods and fields. 68 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 69 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 70 * </ul> 71 * 72 * @author John Rose, JSR 292 EG 73 * @since 1.7 74 */ 75 public class MethodHandles { 76 77 private MethodHandles() { } // do not instantiate 78 79 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 80 81 // See IMPL_LOOKUP below. 82 83 //// Method handle creation from ordinary methods. 84 85 /** 86 * Returns a {@link Lookup lookup object} with 87 * full capabilities to emulate all supported bytecode behaviors of the caller. 88 * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller. 89 * Factory methods on the lookup object can create 90 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 91 * for any member that the caller has access to via bytecodes, 92 * including protected and private fields and methods. 93 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 94 * Do not store it in place where untrusted code can access it. 95 * <p> 96 * This method is caller sensitive, which means that it may return different 97 * values to different callers. 98 * <p> 99 * For any given caller class {@code C}, the lookup object returned by this call 100 * has equivalent capabilities to any lookup object 101 * supplied by the JVM to the bootstrap method of an 102 * <a href="package-summary.html#indyinsn">invokedynamic instruction</a> 103 * executing in the same caller class {@code C}. 104 * @return a lookup object for the caller of this method, with private access 105 */ 106 @CallerSensitive 107 public static Lookup lookup() { 108 return new Lookup(Reflection.getCallerClass()); 109 } 110 111 /** 112 * Returns a {@link Lookup lookup object} which is trusted minimally. 113 * It can only be used to create method handles to public members in 114 * public classes in packages that are exported unconditionally. 115 * <p> 116 * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup 117 * object is in an unnamed module. 118 * Consequently, the lookup context of this lookup object will be the bootstrap 119 * class loader, which means it cannot find user classes. 120 * 121 * <p style="font-size:smaller;"> 122 * <em>Discussion:</em> 123 * The lookup class can be changed to any other class {@code C} using an expression of the form 124 * {@link Lookup#in publicLookup().in(C.class)}. 125 * but may change the lookup context by virtue of changing the class loader. 126 * A public lookup object is always subject to 127 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 128 * Also, it cannot access 129 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 130 * @return a lookup object which is trusted minimally 131 */ 132 public static Lookup publicLookup() { 133 // During VM startup then only classes in the java.base module can be 134 // loaded and linked. This is because java.base exports aren't setup until 135 // the module system is initialized, hence types in the unnamed module 136 // (or any named module) can't link to java/lang/Object. 137 if (!jdk.internal.misc.VM.isModuleSystemInited()) { 138 return new Lookup(Object.class, Lookup.PUBLIC); 139 } else { 140 return LookupHelper.PUBLIC_LOOKUP; 141 } 142 } 143 144 /** 145 * Performs an unchecked "crack" of a 146 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 147 * The result is as if the user had obtained a lookup object capable enough 148 * to crack the target method handle, called 149 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 150 * on the target to obtain its symbolic reference, and then called 151 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 152 * to resolve the symbolic reference to a member. 153 * <p> 154 * If there is a security manager, its {@code checkPermission} method 155 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 156 * @param <T> the desired type of the result, either {@link Member} or a subtype 157 * @param target a direct method handle to crack into symbolic reference components 158 * @param expected a class object representing the desired result type {@code T} 159 * @return a reference to the method, constructor, or field object 160 * @exception SecurityException if the caller is not privileged to call {@code setAccessible} 161 * @exception NullPointerException if either argument is {@code null} 162 * @exception IllegalArgumentException if the target is not a direct method handle 163 * @exception ClassCastException if the member is not of the expected type 164 * @since 1.8 165 */ 166 public static <T extends Member> T 167 reflectAs(Class<T> expected, MethodHandle target) { 168 SecurityManager smgr = System.getSecurityManager(); 169 if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION); 170 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 171 return lookup.revealDirect(target).reflectAs(expected, lookup); 172 } 173 // Copied from AccessibleObject, as used by Method.setAccessible, etc.: 174 private static final java.security.Permission ACCESS_PERMISSION = 175 new ReflectPermission("suppressAccessChecks"); 176 177 /** 178 * A <em>lookup object</em> is a factory for creating method handles, 179 * when the creation requires access checking. 180 * Method handles do not perform 181 * access checks when they are called, but rather when they are created. 182 * Therefore, method handle access 183 * restrictions must be enforced when a method handle is created. 184 * The caller class against which those restrictions are enforced 185 * is known as the {@linkplain #lookupClass lookup class}. 186 * <p> 187 * A lookup class which needs to create method handles will call 188 * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself. 189 * When the {@code Lookup} factory object is created, the identity of the lookup class is 190 * determined, and securely stored in the {@code Lookup} object. 191 * The lookup class (or its delegates) may then use factory methods 192 * on the {@code Lookup} object to create method handles for access-checked members. 193 * This includes all methods, constructors, and fields which are allowed to the lookup class, 194 * even private ones. 195 * 196 * <h1><a name="lookups"></a>Lookup Factory Methods</h1> 197 * The factory methods on a {@code Lookup} object correspond to all major 198 * use cases for methods, constructors, and fields. 199 * Each method handle created by a factory method is the functional 200 * equivalent of a particular <em>bytecode behavior</em>. 201 * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.) 202 * Here is a summary of the correspondence between these factory methods and 203 * the behavior of the resulting method handles: 204 * <table border=1 cellpadding=5 summary="lookup method behaviors"> 205 * <tr> 206 * <th><a name="equiv"></a>lookup expression</th> 207 * <th>member</th> 208 * <th>bytecode behavior</th> 209 * </tr> 210 * <tr> 211 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td> 212 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 213 * </tr> 214 * <tr> 215 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td> 216 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td> 217 * </tr> 218 * <tr> 219 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td> 220 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 221 * </tr> 222 * <tr> 223 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td> 224 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 225 * </tr> 226 * <tr> 227 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td> 228 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 229 * </tr> 230 * <tr> 231 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td> 232 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 233 * </tr> 234 * <tr> 235 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td> 236 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 237 * </tr> 238 * <tr> 239 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td> 240 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 241 * </tr> 242 * <tr> 243 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td> 244 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 245 * </tr> 246 * <tr> 247 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td> 248 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 249 * </tr> 250 * <tr> 251 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 252 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 253 * </tr> 254 * <tr> 255 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td> 256 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 257 * </tr> 258 * <tr> 259 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 260 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 261 * </tr> 262 * <tr> 263 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td> 264 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 265 * </tr> 266 * </table> 267 * 268 * Here, the type {@code C} is the class or interface being searched for a member, 269 * documented as a parameter named {@code refc} in the lookup methods. 270 * The method type {@code MT} is composed from the return type {@code T} 271 * and the sequence of argument types {@code A*}. 272 * The constructor also has a sequence of argument types {@code A*} and 273 * is deemed to return the newly-created object of type {@code C}. 274 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 275 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 276 * if it is present, it is always the leading argument to the method handle invocation. 277 * (In the case of some {@code protected} members, {@code this} may be 278 * restricted in type to the lookup class; see below.) 279 * The name {@code arg} stands for all the other method handle arguments. 280 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 281 * stands for a null reference if the accessed method or field is static, 282 * and {@code this} otherwise. 283 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 284 * for reflective objects corresponding to the given members. 285 * <p> 286 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 287 * as if by {@code ldc CONSTANT_Class}. 288 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 289 * <p> 290 * In cases where the given member is of variable arity (i.e., a method or constructor) 291 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 292 * In all other cases, the returned method handle will be of fixed arity. 293 * <p style="font-size:smaller;"> 294 * <em>Discussion:</em> 295 * The equivalence between looked-up method handles and underlying 296 * class members and bytecode behaviors 297 * can break down in a few ways: 298 * <ul style="font-size:smaller;"> 299 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 300 * the lookup can still succeed, even when there is no equivalent 301 * Java expression or bytecoded constant. 302 * <li>Likewise, if {@code T} or {@code MT} 303 * is not symbolically accessible from the lookup class's loader, 304 * the lookup can still succeed. 305 * For example, lookups for {@code MethodHandle.invokeExact} and 306 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 307 * <li>If there is a security manager installed, it can forbid the lookup 308 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 309 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 310 * constant is not subject to security manager checks. 311 * <li>If the looked-up method has a 312 * <a href="MethodHandle.html#maxarity">very large arity</a>, 313 * the method handle creation may fail, due to the method handle 314 * type having too many parameters. 315 * </ul> 316 * 317 * <h1><a name="access"></a>Access checking</h1> 318 * Access checks are applied in the factory methods of {@code Lookup}, 319 * when a method handle is created. 320 * This is a key difference from the Core Reflection API, since 321 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 322 * performs access checking against every caller, on every call. 323 * <p> 324 * All access checks start from a {@code Lookup} object, which 325 * compares its recorded lookup class against all requests to 326 * create method handles. 327 * A single {@code Lookup} object can be used to create any number 328 * of access-checked method handles, all checked against a single 329 * lookup class. 330 * <p> 331 * A {@code Lookup} object can be shared with other trusted code, 332 * such as a metaobject protocol. 333 * A shared {@code Lookup} object delegates the capability 334 * to create method handles on private members of the lookup class. 335 * Even if privileged code uses the {@code Lookup} object, 336 * the access checking is confined to the privileges of the 337 * original lookup class. 338 * <p> 339 * A lookup can fail, because 340 * the containing class is not accessible to the lookup class, or 341 * because the desired class member is missing, or because the 342 * desired class member is not accessible to the lookup class, or 343 * because the lookup object is not trusted enough to access the member. 344 * In any of these cases, a {@code ReflectiveOperationException} will be 345 * thrown from the attempted lookup. The exact class will be one of 346 * the following: 347 * <ul> 348 * <li>NoSuchMethodException — if a method is requested but does not exist 349 * <li>NoSuchFieldException — if a field is requested but does not exist 350 * <li>IllegalAccessException — if the member exists but an access check fails 351 * </ul> 352 * <p> 353 * In general, the conditions under which a method handle may be 354 * looked up for a method {@code M} are no more restrictive than the conditions 355 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 356 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 357 * a method handle lookup will generally raise a corresponding 358 * checked exception, such as {@code NoSuchMethodException}. 359 * And the effect of invoking the method handle resulting from the lookup 360 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 361 * to executing the compiled, verified, and resolved call to {@code M}. 362 * The same point is true of fields and constructors. 363 * <p style="font-size:smaller;"> 364 * <em>Discussion:</em> 365 * Access checks only apply to named and reflected methods, 366 * constructors, and fields. 367 * Other method handle creation methods, such as 368 * {@link MethodHandle#asType MethodHandle.asType}, 369 * do not require any access checks, and are used 370 * independently of any {@code Lookup} object. 371 * <p> 372 * If the desired member is {@code protected}, the usual JVM rules apply, 373 * including the requirement that the lookup class must be either be in the 374 * same package as the desired member, or must inherit that member. 375 * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.) 376 * In addition, if the desired member is a non-static field or method 377 * in a different package, the resulting method handle may only be applied 378 * to objects of the lookup class or one of its subclasses. 379 * This requirement is enforced by narrowing the type of the leading 380 * {@code this} parameter from {@code C} 381 * (which will necessarily be a superclass of the lookup class) 382 * to the lookup class itself. 383 * <p> 384 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 385 * that the receiver argument must match both the resolved method <em>and</em> 386 * the current class. Again, this requirement is enforced by narrowing the 387 * type of the leading parameter to the resulting method handle. 388 * (See the Java Virtual Machine Specification, section 4.10.1.9.) 389 * <p> 390 * The JVM represents constructors and static initializer blocks as internal methods 391 * with special names ({@code "<init>"} and {@code "<clinit>"}). 392 * The internal syntax of invocation instructions allows them to refer to such internal 393 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 394 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 395 * <p> 396 * In some cases, access between nested classes is obtained by the Java compiler by creating 397 * an wrapper method to access a private method of another class 398 * in the same top-level declaration. 399 * For example, a nested class {@code C.D} 400 * can access private members within other related classes such as 401 * {@code C}, {@code C.D.E}, or {@code C.B}, 402 * but the Java compiler may need to generate wrapper methods in 403 * those related classes. In such cases, a {@code Lookup} object on 404 * {@code C.E} would be unable to those private members. 405 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 406 * which can transform a lookup on {@code C.E} into one on any of those other 407 * classes, without special elevation of privilege. 408 * <p> 409 * The accesses permitted to a given lookup object may be limited, 410 * according to its set of {@link #lookupModes lookupModes}, 411 * to a subset of members normally accessible to the lookup class. 412 * For example, the {@link MethodHandles#publicLookup publicLookup} 413 * method produces a lookup object which is only allowed to access 414 * public members in public classes of exported packages. 415 * The caller sensitive method {@link MethodHandles#lookup lookup} 416 * produces a lookup object with full capabilities relative to 417 * its caller class, to emulate all supported bytecode behaviors. 418 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 419 * with fewer access modes than the original lookup object. 420 * 421 * <p style="font-size:smaller;"> 422 * <a name="privacc"></a> 423 * <em>Discussion of private access:</em> 424 * We say that a lookup has <em>private access</em> 425 * if its {@linkplain #lookupModes lookup modes} 426 * include the possibility of accessing {@code private} members. 427 * As documented in the relevant methods elsewhere, 428 * only lookups with private access possess the following capabilities: 429 * <ul style="font-size:smaller;"> 430 * <li>access private fields, methods, and constructors of the lookup class 431 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 432 * such as {@code Class.forName} 433 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 434 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 435 * for classes accessible to the lookup class 436 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 437 * within the same package member 438 * </ul> 439 * <p style="font-size:smaller;"> 440 * Each of these permissions is a consequence of the fact that a lookup object 441 * with private access can be securely traced back to an originating class, 442 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 443 * can be reliably determined and emulated by method handles. 444 * 445 * <h1><a name="secmgr"></a>Security manager interactions</h1> 446 * Although bytecode instructions can only refer to classes in 447 * a related class loader, this API can search for methods in any 448 * class, as long as a reference to its {@code Class} object is 449 * available. Such cross-loader references are also possible with the 450 * Core Reflection API, and are impossible to bytecode instructions 451 * such as {@code invokestatic} or {@code getfield}. 452 * There is a {@linkplain java.lang.SecurityManager security manager API} 453 * to allow applications to check such cross-loader references. 454 * These checks apply to both the {@code MethodHandles.Lookup} API 455 * and the Core Reflection API 456 * (as found on {@link java.lang.Class Class}). 457 * <p> 458 * If a security manager is present, member and class lookups are subject to 459 * additional checks. 460 * From one to three calls are made to the security manager. 461 * Any of these calls can refuse access by throwing a 462 * {@link java.lang.SecurityException SecurityException}. 463 * Define {@code smgr} as the security manager, 464 * {@code lookc} as the lookup class of the current lookup object, 465 * {@code refc} as the containing class in which the member 466 * is being sought, and {@code defc} as the class in which the 467 * member is actually defined. 468 * (If a class or other type is being accessed, 469 * the {@code refc} and {@code defc} values are the class itself.) 470 * The value {@code lookc} is defined as <em>not present</em> 471 * if the current lookup object does not have 472 * <a href="MethodHandles.Lookup.html#privacc">private access</a>. 473 * The calls are made according to the following rules: 474 * <ul> 475 * <li><b>Step 1:</b> 476 * If {@code lookc} is not present, or if its class loader is not 477 * the same as or an ancestor of the class loader of {@code refc}, 478 * then {@link SecurityManager#checkPackageAccess 479 * smgr.checkPackageAccess(refcPkg)} is called, 480 * where {@code refcPkg} is the package of {@code refc}. 481 * <li><b>Step 2a:</b> 482 * If the retrieved member is not public and 483 * {@code lookc} is not present, then 484 * {@link SecurityManager#checkPermission smgr.checkPermission} 485 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 486 * <li><b>Step 2b:</b> 487 * If the retrieved class has a {@code null} class loader, 488 * and {@code lookc} is not present, then 489 * {@link SecurityManager#checkPermission smgr.checkPermission} 490 * with {@code RuntimePermission("getClassLoader")} is called. 491 * <li><b>Step 3:</b> 492 * If the retrieved member is not public, 493 * and if {@code lookc} is not present, 494 * and if {@code defc} and {@code refc} are different, 495 * then {@link SecurityManager#checkPackageAccess 496 * smgr.checkPackageAccess(defcPkg)} is called, 497 * where {@code defcPkg} is the package of {@code defc}. 498 * </ul> 499 * Security checks are performed after other access checks have passed. 500 * Therefore, the above rules presuppose a member or class that is public, 501 * or else that is being accessed from a lookup class that has 502 * rights to access the member or class. 503 * 504 * <h1><a name="callsens"></a>Caller sensitive methods</h1> 505 * A small number of Java methods have a special property called caller sensitivity. 506 * A <em>caller-sensitive</em> method can behave differently depending on the 507 * identity of its immediate caller. 508 * <p> 509 * If a method handle for a caller-sensitive method is requested, 510 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 511 * but they take account of the lookup class in a special way. 512 * The resulting method handle behaves as if it were called 513 * from an instruction contained in the lookup class, 514 * so that the caller-sensitive method detects the lookup class. 515 * (By contrast, the invoker of the method handle is disregarded.) 516 * Thus, in the case of caller-sensitive methods, 517 * different lookup classes may give rise to 518 * differently behaving method handles. 519 * <p> 520 * In cases where the lookup object is 521 * {@link MethodHandles#publicLookup() publicLookup()}, 522 * or some other lookup object without 523 * <a href="MethodHandles.Lookup.html#privacc">private access</a>, 524 * the lookup class is disregarded. 525 * In such cases, no caller-sensitive method handle can be created, 526 * access is forbidden, and the lookup fails with an 527 * {@code IllegalAccessException}. 528 * <p style="font-size:smaller;"> 529 * <em>Discussion:</em> 530 * For example, the caller-sensitive method 531 * {@link java.lang.Class#forName(String) Class.forName(x)} 532 * can return varying classes or throw varying exceptions, 533 * depending on the class loader of the class that calls it. 534 * A public lookup of {@code Class.forName} will fail, because 535 * there is no reasonable way to determine its bytecode behavior. 536 * <p style="font-size:smaller;"> 537 * If an application caches method handles for broad sharing, 538 * it should use {@code publicLookup()} to create them. 539 * If there is a lookup of {@code Class.forName}, it will fail, 540 * and the application must take appropriate action in that case. 541 * It may be that a later lookup, perhaps during the invocation of a 542 * bootstrap method, can incorporate the specific identity 543 * of the caller, making the method accessible. 544 * <p style="font-size:smaller;"> 545 * The function {@code MethodHandles.lookup} is caller sensitive 546 * so that there can be a secure foundation for lookups. 547 * Nearly all other methods in the JSR 292 API rely on lookup 548 * objects to check access requests. 549 */ 550 public static final 551 class Lookup { 552 /** The class on behalf of whom the lookup is being performed. */ 553 private final Class<?> lookupClass; 554 555 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 556 private final int allowedModes; 557 558 /** A single-bit mask representing {@code public} access, 559 * which may contribute to the result of {@link #lookupModes lookupModes}. 560 * The value, {@code 0x01}, happens to be the same as the value of the 561 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 562 */ 563 public static final int PUBLIC = Modifier.PUBLIC; 564 565 /** A single-bit mask representing {@code private} access, 566 * which may contribute to the result of {@link #lookupModes lookupModes}. 567 * The value, {@code 0x02}, happens to be the same as the value of the 568 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 569 */ 570 public static final int PRIVATE = Modifier.PRIVATE; 571 572 /** A single-bit mask representing {@code protected} access, 573 * which may contribute to the result of {@link #lookupModes lookupModes}. 574 * The value, {@code 0x04}, happens to be the same as the value of the 575 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 576 */ 577 public static final int PROTECTED = Modifier.PROTECTED; 578 579 /** A single-bit mask representing {@code package} access (default access), 580 * which may contribute to the result of {@link #lookupModes lookupModes}. 581 * The value is {@code 0x08}, which does not correspond meaningfully to 582 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 583 */ 584 public static final int PACKAGE = Modifier.STATIC; 585 586 /** A single-bit mask representing {@code module} access (default access), 587 * which may contribute to the result of {@link #lookupModes lookupModes}. 588 * The value is {@code 0x10}, which does not correspond meaningfully to 589 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 590 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 591 * with this lookup mode can access all public types in the module of the 592 * lookup class and public types in packages exported by other modules 593 * to the module of the lookup class. 594 * @since 9 595 */ 596 public static final int MODULE = PACKAGE << 1; 597 598 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE); 599 private static final int TRUSTED = -1; 600 601 private static int fixmods(int mods) { 602 mods &= (ALL_MODES - PACKAGE - MODULE); 603 return (mods != 0) ? mods : (PACKAGE | MODULE); 604 } 605 606 /** Tells which class is performing the lookup. It is this class against 607 * which checks are performed for visibility and access permissions. 608 * <p> 609 * The class implies a maximum level of access permission, 610 * but the permissions may be additionally limited by the bitmask 611 * {@link #lookupModes lookupModes}, which controls whether non-public members 612 * can be accessed. 613 * @return the lookup class, on behalf of which this lookup object finds members 614 */ 615 public Class<?> lookupClass() { 616 return lookupClass; 617 } 618 619 // This is just for calling out to MethodHandleImpl. 620 private Class<?> lookupClassOrNull() { 621 return (allowedModes == TRUSTED) ? null : lookupClass; 622 } 623 624 /** Tells which access-protection classes of members this lookup object can produce. 625 * The result is a bit-mask of the bits 626 * {@linkplain #PUBLIC PUBLIC (0x01)}, 627 * {@linkplain #PRIVATE PRIVATE (0x02)}, 628 * {@linkplain #PROTECTED PROTECTED (0x04)}, 629 * {@linkplain #PACKAGE PACKAGE (0x08)}, 630 * and {@linkplain #MODULE MODULE (0x10)}. 631 * <p> 632 * A freshly-created lookup object 633 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} 634 * has all possible bits set, since the caller class can access all its own members, 635 * all public types in the caller's module, and all public types in packages exported 636 * by other modules to the caller's module. 637 * A lookup object on a new lookup class 638 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 639 * may have some mode bits set to zero. 640 * The purpose of this is to restrict access via the new lookup object, 641 * so that it can access only names which can be reached by the original 642 * lookup object, and also by the new lookup class. 643 * @return the lookup modes, which limit the kinds of access performed by this lookup object 644 */ 645 public int lookupModes() { 646 return allowedModes & ALL_MODES; 647 } 648 649 /** Embody the current class (the lookupClass) as a lookup class 650 * for method handle creation. 651 * Must be called by from a method in this package, 652 * which in turn is called by a method not in this package. 653 */ 654 Lookup(Class<?> lookupClass) { 655 this(lookupClass, ALL_MODES); 656 // make sure we haven't accidentally picked up a privileged class: 657 checkUnprivilegedlookupClass(lookupClass, ALL_MODES); 658 } 659 660 private Lookup(Class<?> lookupClass, int allowedModes) { 661 this.lookupClass = lookupClass; 662 this.allowedModes = allowedModes; 663 } 664 665 /** 666 * Creates a lookup on the specified new lookup class. 667 * The resulting object will report the specified 668 * class as its own {@link #lookupClass lookupClass}. 669 * <p> 670 * However, the resulting {@code Lookup} object is guaranteed 671 * to have no more access capabilities than the original. 672 * In particular, access capabilities can be lost as follows:<ul> 673 * <li>If the lookup class for this {@code Lookup} is not in a named module, 674 * and the new lookup class is in a named module {@code M}, then no members in 675 * {@code M}'s non-exported packages will be accessible. 676 * <li>If the lookup for this {@code Lookup} is in a named module, and the 677 * new lookup class is in a different module {@code M}, then no members, not even 678 * public members in {@code M}'s exported packages, will be accessible. 679 * <li>If the new lookup class differs from the old one, 680 * protected members will not be accessible by virtue of inheritance. 681 * (Protected members may continue to be accessible because of package sharing.) 682 * <li>If the new lookup class is in a different package 683 * than the old one, protected and default (package) members will not be accessible. 684 * <li>If the new lookup class is not within the same package member 685 * as the old one, private members will not be accessible. 686 * <li>If the new lookup class is not accessible to the old lookup class, 687 * then no members, not even public members, will be accessible. 688 * (In all other cases, public members will continue to be accessible.) 689 * </ul> 690 * <p> 691 * The resulting lookup's capabilities for loading classes 692 * (used during {@link #findClass} invocations) 693 * are determined by the lookup class' loader, 694 * which may change due to this operation. 695 * 696 * @param requestedLookupClass the desired lookup class for the new lookup object 697 * @return a lookup object which reports the desired lookup class 698 * @throws NullPointerException if the argument is null 699 */ 700 public Lookup in(Class<?> requestedLookupClass) { 701 Objects.requireNonNull(requestedLookupClass); 702 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 703 return new Lookup(requestedLookupClass, ALL_MODES); 704 if (requestedLookupClass == this.lookupClass) 705 return this; // keep same capabilities 706 707 int newModes = (allowedModes & (ALL_MODES & ~PROTECTED)); 708 if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) { 709 // Allowed to teleport from an unnamed to a named module but resulting 710 // Lookup has no access to module private members 711 if (this.lookupClass.getModule().isNamed()) { 712 newModes = 0; 713 } else { 714 newModes &= ~MODULE; 715 } 716 } 717 if ((newModes & PACKAGE) != 0 718 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 719 newModes &= ~(PACKAGE|PRIVATE); 720 } 721 // Allow nestmate lookups to be created without special privilege: 722 if ((newModes & PRIVATE) != 0 723 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 724 newModes &= ~PRIVATE; 725 } 726 if ((newModes & PUBLIC) != 0 727 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) { 728 // The requested class it not accessible from the lookup class. 729 // No permissions. 730 newModes = 0; 731 } 732 733 checkUnprivilegedlookupClass(requestedLookupClass, newModes); 734 return new Lookup(requestedLookupClass, newModes); 735 } 736 737 // Make sure outer class is initialized first. 738 static { IMPL_NAMES.getClass(); } 739 740 /** Package-private version of lookup which is trusted. */ 741 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED); 742 743 private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) { 744 String name = lookupClass.getName(); 745 if (name.startsWith("java.lang.invoke.")) 746 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 747 748 // For caller-sensitive MethodHandles.lookup() disallow lookup from 749 // restricted packages. This a fragile and blunt approach. 750 // TODO replace with a more formal and less fragile mechanism 751 // that does not bluntly restrict classes under packages within 752 // java.base from looking up MethodHandles or VarHandles. 753 if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) { 754 if ((name.startsWith("java.") && !name.startsWith("java.util.concurrent.")) || 755 (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) { 756 throw newIllegalArgumentException("illegal lookupClass: " + lookupClass); 757 } 758 } 759 } 760 761 /** 762 * Displays the name of the class from which lookups are to be made. 763 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 764 * If there are restrictions on the access permitted to this lookup, 765 * this is indicated by adding a suffix to the class name, consisting 766 * of a slash and a keyword. The keyword represents the strongest 767 * allowed access, and is chosen as follows: 768 * <ul> 769 * <li>If no access is allowed, the suffix is "/noaccess". 770 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 771 * <li>If only public and module access are allowed, the suffix is "/module". 772 * <li>If only public, module and package access are allowed, the suffix is "/package". 773 * <li>If only public, module, package, and private access are allowed, the suffix is "/private". 774 * </ul> 775 * If none of the above cases apply, it is the case that full 776 * access (public, module, package, private, and protected) is allowed. 777 * In this case, no suffix is added. 778 * This is true only of an object obtained originally from 779 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 780 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 781 * always have restricted access, and will display a suffix. 782 * <p> 783 * (It may seem strange that protected access should be 784 * stronger than private access. Viewed independently from 785 * package access, protected access is the first to be lost, 786 * because it requires a direct subclass relationship between 787 * caller and callee.) 788 * @see #in 789 */ 790 @Override 791 public String toString() { 792 String cname = lookupClass.getName(); 793 switch (allowedModes) { 794 case 0: // no privileges 795 return cname + "/noaccess"; 796 case PUBLIC: 797 return cname + "/public"; 798 case PUBLIC|MODULE: 799 return cname + "/module"; 800 case PUBLIC|MODULE|PACKAGE: 801 return cname + "/package"; 802 case ALL_MODES & ~PROTECTED: 803 return cname + "/private"; 804 case ALL_MODES: 805 return cname; 806 case TRUSTED: 807 return "/trusted"; // internal only; not exported 808 default: // Should not happen, but it's a bitfield... 809 cname = cname + "/" + Integer.toHexString(allowedModes); 810 assert(false) : cname; 811 return cname; 812 } 813 } 814 815 /** 816 * Produces a method handle for a static method. 817 * The type of the method handle will be that of the method. 818 * (Since static methods do not take receivers, there is no 819 * additional receiver argument inserted into the method handle type, 820 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 821 * The method and all its argument types must be accessible to the lookup object. 822 * <p> 823 * The returned method handle will have 824 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 825 * the method's variable arity modifier bit ({@code 0x0080}) is set. 826 * <p> 827 * If the returned method handle is invoked, the method's class will 828 * be initialized, if it has not already been initialized. 829 * <p><b>Example:</b> 830 * <blockquote><pre>{@code 831 import static java.lang.invoke.MethodHandles.*; 832 import static java.lang.invoke.MethodType.*; 833 ... 834 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 835 "asList", methodType(List.class, Object[].class)); 836 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 837 * }</pre></blockquote> 838 * @param refc the class from which the method is accessed 839 * @param name the name of the method 840 * @param type the type of the method 841 * @return the desired method handle 842 * @throws NoSuchMethodException if the method does not exist 843 * @throws IllegalAccessException if access checking fails, 844 * or if the method is not {@code static}, 845 * or if the method's variable arity modifier bit 846 * is set and {@code asVarargsCollector} fails 847 * @exception SecurityException if a security manager is present and it 848 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 849 * @throws NullPointerException if any argument is null 850 */ 851 public 852 MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 853 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 854 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method)); 855 } 856 857 /** 858 * Produces a method handle for a virtual method. 859 * The type of the method handle will be that of the method, 860 * with the receiver type (usually {@code refc}) prepended. 861 * The method and all its argument types must be accessible to the lookup object. 862 * <p> 863 * When called, the handle will treat the first argument as a receiver 864 * and dispatch on the receiver's type to determine which method 865 * implementation to enter. 866 * (The dispatching action is identical with that performed by an 867 * {@code invokevirtual} or {@code invokeinterface} instruction.) 868 * <p> 869 * The first argument will be of type {@code refc} if the lookup 870 * class has full privileges to access the member. Otherwise 871 * the member must be {@code protected} and the first argument 872 * will be restricted in type to the lookup class. 873 * <p> 874 * The returned method handle will have 875 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 876 * the method's variable arity modifier bit ({@code 0x0080}) is set. 877 * <p> 878 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 879 * instructions and method handles produced by {@code findVirtual}, 880 * if the class is {@code MethodHandle} and the name string is 881 * {@code invokeExact} or {@code invoke}, the resulting 882 * method handle is equivalent to one produced by 883 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 884 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 885 * with the same {@code type} argument. 886 * <p> 887 * If the class is {@code VarHandle} and the name string corresponds to 888 * the name of a signature-polymorphic access mode method, the resulting 889 * method handle is equivalent to one produced by 890 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 891 * the access mode corresponding to the name string and with the same 892 * {@code type} arguments. 893 * <p> 894 * <b>Example:</b> 895 * <blockquote><pre>{@code 896 import static java.lang.invoke.MethodHandles.*; 897 import static java.lang.invoke.MethodType.*; 898 ... 899 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 900 "concat", methodType(String.class, String.class)); 901 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 902 "hashCode", methodType(int.class)); 903 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 904 "hashCode", methodType(int.class)); 905 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 906 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 907 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 908 // interface method: 909 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 910 "subSequence", methodType(CharSequence.class, int.class, int.class)); 911 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 912 // constructor "internal method" must be accessed differently: 913 MethodType MT_newString = methodType(void.class); //()V for new String() 914 try { assertEquals("impossible", lookup() 915 .findVirtual(String.class, "<init>", MT_newString)); 916 } catch (NoSuchMethodException ex) { } // OK 917 MethodHandle MH_newString = publicLookup() 918 .findConstructor(String.class, MT_newString); 919 assertEquals("", (String) MH_newString.invokeExact()); 920 * }</pre></blockquote> 921 * 922 * @param refc the class or interface from which the method is accessed 923 * @param name the name of the method 924 * @param type the type of the method, with the receiver argument omitted 925 * @return the desired method handle 926 * @throws NoSuchMethodException if the method does not exist 927 * @throws IllegalAccessException if access checking fails, 928 * or if the method is {@code static}, 929 * or if the method is {@code private} method of interface, 930 * or if the method's variable arity modifier bit 931 * is set and {@code asVarargsCollector} fails 932 * @exception SecurityException if a security manager is present and it 933 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 934 * @throws NullPointerException if any argument is null 935 */ 936 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 937 if (refc == MethodHandle.class) { 938 MethodHandle mh = findVirtualForMH(name, type); 939 if (mh != null) return mh; 940 } else if (refc == VarHandle.class) { 941 MethodHandle mh = findVirtualForVH(name, type); 942 if (mh != null) return mh; 943 } 944 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 945 MemberName method = resolveOrFail(refKind, refc, name, type); 946 return getDirectMethod(refKind, refc, method, findBoundCallerClass(method)); 947 } 948 private MethodHandle findVirtualForMH(String name, MethodType type) { 949 // these names require special lookups because of the implicit MethodType argument 950 if ("invoke".equals(name)) 951 return invoker(type); 952 if ("invokeExact".equals(name)) 953 return exactInvoker(type); 954 if ("invokeBasic".equals(name)) 955 return basicInvoker(type); 956 assert(!MemberName.isMethodHandleInvokeName(name)); 957 return null; 958 } 959 private MethodHandle findVirtualForVH(String name, MethodType type) { 960 try { 961 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 962 } catch (IllegalArgumentException e) { 963 return null; 964 } 965 } 966 967 /** 968 * Produces a method handle which creates an object and initializes it, using 969 * the constructor of the specified type. 970 * The parameter types of the method handle will be those of the constructor, 971 * while the return type will be a reference to the constructor's class. 972 * The constructor and all its argument types must be accessible to the lookup object. 973 * <p> 974 * The requested type must have a return type of {@code void}. 975 * (This is consistent with the JVM's treatment of constructor type descriptors.) 976 * <p> 977 * The returned method handle will have 978 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 979 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 980 * <p> 981 * If the returned method handle is invoked, the constructor's class will 982 * be initialized, if it has not already been initialized. 983 * <p><b>Example:</b> 984 * <blockquote><pre>{@code 985 import static java.lang.invoke.MethodHandles.*; 986 import static java.lang.invoke.MethodType.*; 987 ... 988 MethodHandle MH_newArrayList = publicLookup().findConstructor( 989 ArrayList.class, methodType(void.class, Collection.class)); 990 Collection orig = Arrays.asList("x", "y"); 991 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 992 assert(orig != copy); 993 assertEquals(orig, copy); 994 // a variable-arity constructor: 995 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 996 ProcessBuilder.class, methodType(void.class, String[].class)); 997 ProcessBuilder pb = (ProcessBuilder) 998 MH_newProcessBuilder.invoke("x", "y", "z"); 999 assertEquals("[x, y, z]", pb.command().toString()); 1000 * }</pre></blockquote> 1001 * @param refc the class or interface from which the method is accessed 1002 * @param type the type of the method, with the receiver argument omitted, and a void return type 1003 * @return the desired method handle 1004 * @throws NoSuchMethodException if the constructor does not exist 1005 * @throws IllegalAccessException if access checking fails 1006 * or if the method's variable arity modifier bit 1007 * is set and {@code asVarargsCollector} fails 1008 * @exception SecurityException if a security manager is present and it 1009 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1010 * @throws NullPointerException if any argument is null 1011 */ 1012 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1013 if (refc.isArray()) { 1014 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 1015 } 1016 String name = "<init>"; 1017 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 1018 return getDirectConstructor(refc, ctor); 1019 } 1020 1021 /** 1022 * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static 1023 * initializer of the class is not run. 1024 * <p> 1025 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class 1026 * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to 1027 * load the requested class, and then determines whether the class is accessible to this lookup object. 1028 * 1029 * @param targetName the fully qualified name of the class to be looked up. 1030 * @return the requested class. 1031 * @exception SecurityException if a security manager is present and it 1032 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1033 * @throws LinkageError if the linkage fails 1034 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 1035 * @throws IllegalAccessException if the class is not accessible, using the allowed access 1036 * modes. 1037 * @exception SecurityException if a security manager is present and it 1038 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1039 * @since 9 1040 */ 1041 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 1042 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 1043 return accessClass(targetClass); 1044 } 1045 1046 /** 1047 * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The 1048 * static initializer of the class is not run. 1049 * <p> 1050 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the 1051 * {@linkplain #lookupModes() lookup modes}. 1052 * 1053 * @param targetClass the class to be access-checked 1054 * 1055 * @return the class that has been access-checked 1056 * 1057 * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access 1058 * modes. 1059 * @exception SecurityException if a security manager is present and it 1060 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1061 * @since 9 1062 */ 1063 public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException { 1064 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) { 1065 throw new MemberName(targetClass).makeAccessException("access violation", this); 1066 } 1067 checkSecurityManager(targetClass, null); 1068 return targetClass; 1069 } 1070 1071 /** 1072 * Produces an early-bound method handle for a virtual method. 1073 * It will bypass checks for overriding methods on the receiver, 1074 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1075 * instruction from within the explicitly specified {@code specialCaller}. 1076 * The type of the method handle will be that of the method, 1077 * with a suitably restricted receiver type prepended. 1078 * (The receiver type will be {@code specialCaller} or a subtype.) 1079 * The method and all its argument types must be accessible 1080 * to the lookup object. 1081 * <p> 1082 * Before method resolution, 1083 * if the explicitly specified caller class is not identical with the 1084 * lookup class, or if this lookup object does not have 1085 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1086 * privileges, the access fails. 1087 * <p> 1088 * The returned method handle will have 1089 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1090 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1091 * <p style="font-size:smaller;"> 1092 * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API, 1093 * even though the {@code invokespecial} instruction can refer to them 1094 * in special circumstances. Use {@link #findConstructor findConstructor} 1095 * to access instance initialization methods in a safe manner.)</em> 1096 * <p><b>Example:</b> 1097 * <blockquote><pre>{@code 1098 import static java.lang.invoke.MethodHandles.*; 1099 import static java.lang.invoke.MethodType.*; 1100 ... 1101 static class Listie extends ArrayList { 1102 public String toString() { return "[wee Listie]"; } 1103 static Lookup lookup() { return MethodHandles.lookup(); } 1104 } 1105 ... 1106 // no access to constructor via invokeSpecial: 1107 MethodHandle MH_newListie = Listie.lookup() 1108 .findConstructor(Listie.class, methodType(void.class)); 1109 Listie l = (Listie) MH_newListie.invokeExact(); 1110 try { assertEquals("impossible", Listie.lookup().findSpecial( 1111 Listie.class, "<init>", methodType(void.class), Listie.class)); 1112 } catch (NoSuchMethodException ex) { } // OK 1113 // access to super and self methods via invokeSpecial: 1114 MethodHandle MH_super = Listie.lookup().findSpecial( 1115 ArrayList.class, "toString" , methodType(String.class), Listie.class); 1116 MethodHandle MH_this = Listie.lookup().findSpecial( 1117 Listie.class, "toString" , methodType(String.class), Listie.class); 1118 MethodHandle MH_duper = Listie.lookup().findSpecial( 1119 Object.class, "toString" , methodType(String.class), Listie.class); 1120 assertEquals("[]", (String) MH_super.invokeExact(l)); 1121 assertEquals(""+l, (String) MH_this.invokeExact(l)); 1122 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 1123 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 1124 String.class, "toString", methodType(String.class), Listie.class)); 1125 } catch (IllegalAccessException ex) { } // OK 1126 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 1127 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 1128 * }</pre></blockquote> 1129 * 1130 * @param refc the class or interface from which the method is accessed 1131 * @param name the name of the method (which must not be "<init>") 1132 * @param type the type of the method, with the receiver argument omitted 1133 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 1134 * @return the desired method handle 1135 * @throws NoSuchMethodException if the method does not exist 1136 * @throws IllegalAccessException if access checking fails, 1137 * or if the method is {@code static}, 1138 * or if the method's variable arity modifier bit 1139 * is set and {@code asVarargsCollector} fails 1140 * @exception SecurityException if a security manager is present and it 1141 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1142 * @throws NullPointerException if any argument is null 1143 */ 1144 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 1145 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 1146 checkSpecialCaller(specialCaller, refc); 1147 Lookup specialLookup = this.in(specialCaller); 1148 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 1149 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); 1150 } 1151 1152 /** 1153 * Produces a method handle giving read access to a non-static field. 1154 * The type of the method handle will have a return type of the field's 1155 * value type. 1156 * The method handle's single argument will be the instance containing 1157 * the field. 1158 * Access checking is performed immediately on behalf of the lookup class. 1159 * @param refc the class or interface from which the method is accessed 1160 * @param name the field's name 1161 * @param type the field's type 1162 * @return a method handle which can load values from the field 1163 * @throws NoSuchFieldException if the field does not exist 1164 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1165 * @exception SecurityException if a security manager is present and it 1166 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1167 * @throws NullPointerException if any argument is null 1168 * @see #findVarHandle(Class, String, Class) 1169 */ 1170 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1171 MemberName field = resolveOrFail(REF_getField, refc, name, type); 1172 return getDirectField(REF_getField, refc, field); 1173 } 1174 1175 /** 1176 * Produces a method handle giving write access to a non-static field. 1177 * The type of the method handle will have a void return type. 1178 * The method handle will take two arguments, the instance containing 1179 * the field, and the value to be stored. 1180 * The second argument will be of the field's value type. 1181 * Access checking is performed immediately on behalf of the lookup class. 1182 * @param refc the class or interface from which the method is accessed 1183 * @param name the field's name 1184 * @param type the field's type 1185 * @return a method handle which can store values into the field 1186 * @throws NoSuchFieldException if the field does not exist 1187 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1188 * @exception SecurityException if a security manager is present and it 1189 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1190 * @throws NullPointerException if any argument is null 1191 * @see #findVarHandle(Class, String, Class) 1192 */ 1193 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1194 MemberName field = resolveOrFail(REF_putField, refc, name, type); 1195 return getDirectField(REF_putField, refc, field); 1196 } 1197 1198 /** 1199 * Produces a VarHandle giving access to non-static fields of type 1200 * {@code T} declared by a receiver class of type {@code R}, supporting 1201 * shape {@code (R : T)}. 1202 * <p> 1203 * Access checking is performed immediately on behalf of the lookup 1204 * class. 1205 * <p> 1206 * Certain access modes of the returned VarHandle are unsupported under 1207 * the following conditions: 1208 * <ul> 1209 * <li>if the field is declared {@code final}, then the write, atomic 1210 * update, and numeric atomic update access modes are unsupported. 1211 * <li>if the field type is anything other than {@code int}, 1212 * {@code long} or a reference type, then atomic update access modes 1213 * are unsupported. (Future major platform releases of the JDK may 1214 * support additional types for certain currently unsupported access 1215 * modes.) 1216 * <li>if the field type is anything other than {@code int} or 1217 * {@code long}, then numeric atomic update access modes are 1218 * unsupported. (Future major platform releases of the JDK may 1219 * support additional numeric types for certain currently 1220 * unsupported access modes.) 1221 * </ul> 1222 * <p> 1223 * If the field is declared {@code volatile} then the returned VarHandle 1224 * will override access to the field (effectively ignore the 1225 * {@code volatile} declaration) in accordance to it's specified 1226 * access modes. 1227 * @param recv the receiver class, of type {@code R}, that declares the 1228 * non-static field 1229 * @param name the field's name 1230 * @param type the field's type, of type {@code T} 1231 * @return a VarHandle giving access to non-static fields. 1232 * @throws NoSuchFieldException if the field does not exist 1233 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1234 * @exception SecurityException if a security manager is present and it 1235 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1236 * @throws NullPointerException if any argument is null 1237 * @since 9 1238 */ 1239 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1240 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 1241 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 1242 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 1243 } 1244 1245 /** 1246 * Produces a method handle giving read access to a static field. 1247 * The type of the method handle will have a return type of the field's 1248 * value type. 1249 * The method handle will take no arguments. 1250 * Access checking is performed immediately on behalf of the lookup class. 1251 * <p> 1252 * If the returned method handle is invoked, the field's class will 1253 * be initialized, if it has not already been initialized. 1254 * @param refc the class or interface from which the method is accessed 1255 * @param name the field's name 1256 * @param type the field's type 1257 * @return a method handle which can load values from the field 1258 * @throws NoSuchFieldException if the field does not exist 1259 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1260 * @exception SecurityException if a security manager is present and it 1261 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1262 * @throws NullPointerException if any argument is null 1263 */ 1264 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1265 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 1266 return getDirectField(REF_getStatic, refc, field); 1267 } 1268 1269 /** 1270 * Produces a method handle giving write access to a static field. 1271 * The type of the method handle will have a void return type. 1272 * The method handle will take a single 1273 * argument, of the field's value type, the value to be stored. 1274 * Access checking is performed immediately on behalf of the lookup class. 1275 * <p> 1276 * If the returned method handle is invoked, the field's class will 1277 * be initialized, if it has not already been initialized. 1278 * @param refc the class or interface from which the method is accessed 1279 * @param name the field's name 1280 * @param type the field's type 1281 * @return a method handle which can store values into the field 1282 * @throws NoSuchFieldException if the field does not exist 1283 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1284 * @exception SecurityException if a security manager is present and it 1285 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1286 * @throws NullPointerException if any argument is null 1287 */ 1288 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1289 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 1290 return getDirectField(REF_putStatic, refc, field); 1291 } 1292 1293 /** 1294 * Produces a VarHandle giving access to a static field of type 1295 * {@code T} declared by a given declaring class, supporting shape 1296 * {@code ((empty) : T)}. 1297 * <p> 1298 * Access checking is performed immediately on behalf of the lookup 1299 * class. 1300 * <p> 1301 * If the returned VarHandle is operated on, the declaring class will be 1302 * initialized, if it has not already been initialized. 1303 * <p> 1304 * Certain access modes of the returned VarHandle are unsupported under 1305 * the following conditions: 1306 * <ul> 1307 * <li>if the field is declared {@code final}, then the write, atomic 1308 * update, and numeric atomic update access modes are unsupported. 1309 * <li>if the field type is anything other than {@code int}, 1310 * {@code long} or a reference type, then atomic update access modes 1311 * are unsupported. (Future major platform releases of the JDK may 1312 * support additional types for certain currently unsupported access 1313 * modes.) 1314 * <li>if the field type is anything other than {@code int} or 1315 * {@code long}, then numeric atomic update access modes are 1316 * unsupported. (Future major platform releases of the JDK may 1317 * support additional numeric types for certain currently 1318 * unsupported access modes.) 1319 * </ul> 1320 * <p> 1321 * If the field is declared {@code volatile} then the returned VarHandle 1322 * will override access to the field (effectively ignore the 1323 * {@code volatile} declaration) in accordance to it's specified 1324 * access modes. 1325 * @param decl the class that declares the static field 1326 * @param name the field's name 1327 * @param type the field's type, of type {@code T} 1328 * @return a VarHandle giving access to a static field 1329 * @throws NoSuchFieldException if the field does not exist 1330 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1331 * @exception SecurityException if a security manager is present and it 1332 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1333 * @throws NullPointerException if any argument is null 1334 * @since 9 1335 */ 1336 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1337 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 1338 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 1339 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 1340 } 1341 1342 /** 1343 * Produces an early-bound method handle for a non-static method. 1344 * The receiver must have a supertype {@code defc} in which a method 1345 * of the given name and type is accessible to the lookup class. 1346 * The method and all its argument types must be accessible to the lookup object. 1347 * The type of the method handle will be that of the method, 1348 * without any insertion of an additional receiver parameter. 1349 * The given receiver will be bound into the method handle, 1350 * so that every call to the method handle will invoke the 1351 * requested method on the given receiver. 1352 * <p> 1353 * The returned method handle will have 1354 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1355 * the method's variable arity modifier bit ({@code 0x0080}) is set 1356 * <em>and</em> the trailing array argument is not the only argument. 1357 * (If the trailing array argument is the only argument, 1358 * the given receiver value will be bound to it.) 1359 * <p> 1360 * This is equivalent to the following code: 1361 * <blockquote><pre>{@code 1362 import static java.lang.invoke.MethodHandles.*; 1363 import static java.lang.invoke.MethodType.*; 1364 ... 1365 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 1366 MethodHandle mh1 = mh0.bindTo(receiver); 1367 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 1368 return mh1; 1369 * }</pre></blockquote> 1370 * where {@code defc} is either {@code receiver.getClass()} or a super 1371 * type of that class, in which the requested method is accessible 1372 * to the lookup class. 1373 * (Note that {@code bindTo} does not preserve variable arity.) 1374 * @param receiver the object from which the method is accessed 1375 * @param name the name of the method 1376 * @param type the type of the method, with the receiver argument omitted 1377 * @return the desired method handle 1378 * @throws NoSuchMethodException if the method does not exist 1379 * @throws IllegalAccessException if access checking fails 1380 * or if the method's variable arity modifier bit 1381 * is set and {@code asVarargsCollector} fails 1382 * @exception SecurityException if a security manager is present and it 1383 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1384 * @throws NullPointerException if any argument is null 1385 * @see MethodHandle#bindTo 1386 * @see #findVirtual 1387 */ 1388 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1389 Class<? extends Object> refc = receiver.getClass(); // may get NPE 1390 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 1391 MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); 1392 return mh.bindArgumentL(0, receiver).setVarargs(method); 1393 } 1394 1395 /** 1396 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1397 * to <i>m</i>, if the lookup class has permission. 1398 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 1399 * If <i>m</i> is virtual, overriding is respected on every call. 1400 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 1401 * The type of the method handle will be that of the method, 1402 * with the receiver type prepended (but only if it is non-static). 1403 * If the method's {@code accessible} flag is not set, 1404 * access checking is performed immediately on behalf of the lookup class. 1405 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 1406 * <p> 1407 * The returned method handle will have 1408 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1409 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1410 * <p> 1411 * If <i>m</i> is static, and 1412 * if the returned method handle is invoked, the method's class will 1413 * be initialized, if it has not already been initialized. 1414 * @param m the reflected method 1415 * @return a method handle which can invoke the reflected method 1416 * @throws IllegalAccessException if access checking fails 1417 * or if the method's variable arity modifier bit 1418 * is set and {@code asVarargsCollector} fails 1419 * @throws NullPointerException if the argument is null 1420 */ 1421 public MethodHandle unreflect(Method m) throws IllegalAccessException { 1422 if (m.getDeclaringClass() == MethodHandle.class) { 1423 MethodHandle mh = unreflectForMH(m); 1424 if (mh != null) return mh; 1425 } 1426 if (m.getDeclaringClass() == VarHandle.class) { 1427 MethodHandle mh = unreflectForVH(m); 1428 if (mh != null) return mh; 1429 } 1430 MemberName method = new MemberName(m); 1431 byte refKind = method.getReferenceKind(); 1432 if (refKind == REF_invokeSpecial) 1433 refKind = REF_invokeVirtual; 1434 assert(method.isMethod()); 1435 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 1436 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1437 } 1438 private MethodHandle unreflectForMH(Method m) { 1439 // these names require special lookups because they throw UnsupportedOperationException 1440 if (MemberName.isMethodHandleInvokeName(m.getName())) 1441 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 1442 return null; 1443 } 1444 private MethodHandle unreflectForVH(Method m) { 1445 // these names require special lookups because they throw UnsupportedOperationException 1446 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 1447 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 1448 return null; 1449 } 1450 1451 /** 1452 * Produces a method handle for a reflected method. 1453 * It will bypass checks for overriding methods on the receiver, 1454 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1455 * instruction from within the explicitly specified {@code specialCaller}. 1456 * The type of the method handle will be that of the method, 1457 * with a suitably restricted receiver type prepended. 1458 * (The receiver type will be {@code specialCaller} or a subtype.) 1459 * If the method's {@code accessible} flag is not set, 1460 * access checking is performed immediately on behalf of the lookup class, 1461 * as if {@code invokespecial} instruction were being linked. 1462 * <p> 1463 * Before method resolution, 1464 * if the explicitly specified caller class is not identical with the 1465 * lookup class, or if this lookup object does not have 1466 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1467 * privileges, the access fails. 1468 * <p> 1469 * The returned method handle will have 1470 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1471 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1472 * @param m the reflected method 1473 * @param specialCaller the class nominally calling the method 1474 * @return a method handle which can invoke the reflected method 1475 * @throws IllegalAccessException if access checking fails, 1476 * or if the method is {@code static}, 1477 * or if the method's variable arity modifier bit 1478 * is set and {@code asVarargsCollector} fails 1479 * @throws NullPointerException if any argument is null 1480 */ 1481 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 1482 checkSpecialCaller(specialCaller, null); 1483 Lookup specialLookup = this.in(specialCaller); 1484 MemberName method = new MemberName(m, true); 1485 assert(method.isMethod()); 1486 // ignore m.isAccessible: this is a new kind of access 1487 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1488 } 1489 1490 /** 1491 * Produces a method handle for a reflected constructor. 1492 * The type of the method handle will be that of the constructor, 1493 * with the return type changed to the declaring class. 1494 * The method handle will perform a {@code newInstance} operation, 1495 * creating a new instance of the constructor's class on the 1496 * arguments passed to the method handle. 1497 * <p> 1498 * If the constructor's {@code accessible} flag is not set, 1499 * access checking is performed immediately on behalf of the lookup class. 1500 * <p> 1501 * The returned method handle will have 1502 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1503 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 1504 * <p> 1505 * If the returned method handle is invoked, the constructor's class will 1506 * be initialized, if it has not already been initialized. 1507 * @param c the reflected constructor 1508 * @return a method handle which can invoke the reflected constructor 1509 * @throws IllegalAccessException if access checking fails 1510 * or if the method's variable arity modifier bit 1511 * is set and {@code asVarargsCollector} fails 1512 * @throws NullPointerException if the argument is null 1513 */ 1514 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 1515 MemberName ctor = new MemberName(c); 1516 assert(ctor.isConstructor()); 1517 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 1518 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 1519 } 1520 1521 /** 1522 * Produces a method handle giving read access to a reflected field. 1523 * The type of the method handle will have a return type of the field's 1524 * value type. 1525 * If the field is static, the method handle will take no arguments. 1526 * Otherwise, its single argument will be the instance containing 1527 * the field. 1528 * If the field's {@code accessible} flag is not set, 1529 * access checking is performed immediately on behalf of the lookup class. 1530 * <p> 1531 * If the field is static, and 1532 * if the returned method handle is invoked, the field's class will 1533 * be initialized, if it has not already been initialized. 1534 * @param f the reflected field 1535 * @return a method handle which can load values from the reflected field 1536 * @throws IllegalAccessException if access checking fails 1537 * @throws NullPointerException if the argument is null 1538 */ 1539 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 1540 return unreflectField(f, false); 1541 } 1542 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 1543 MemberName field = new MemberName(f, isSetter); 1544 assert(isSetter 1545 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 1546 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 1547 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 1548 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 1549 } 1550 1551 /** 1552 * Produces a method handle giving write access to a reflected field. 1553 * The type of the method handle will have a void return type. 1554 * If the field is static, the method handle will take a single 1555 * argument, of the field's value type, the value to be stored. 1556 * Otherwise, the two arguments will be the instance containing 1557 * the field, and the value to be stored. 1558 * If the field's {@code accessible} flag is not set, 1559 * access checking is performed immediately on behalf of the lookup class. 1560 * <p> 1561 * If the field is static, and 1562 * if the returned method handle is invoked, the field's class will 1563 * be initialized, if it has not already been initialized. 1564 * @param f the reflected field 1565 * @return a method handle which can store values into the reflected field 1566 * @throws IllegalAccessException if access checking fails 1567 * @throws NullPointerException if the argument is null 1568 */ 1569 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 1570 return unreflectField(f, true); 1571 } 1572 1573 /** 1574 * Produces a VarHandle that accesses fields of type {@code T} declared 1575 * by a class of type {@code R}, as described by the given reflected 1576 * field. 1577 * If the field is non-static the VarHandle supports a shape of 1578 * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}. 1579 * <p> 1580 * Access checking is performed immediately on behalf of the lookup 1581 * class, regardless of the value of the field's {@code accessible} 1582 * flag. 1583 * <p> 1584 * If the field is static, and if the returned VarHandle is operated 1585 * on, the field's declaring class will be initialized, if it has not 1586 * already been initialized. 1587 * <p> 1588 * Certain access modes of the returned VarHandle are unsupported under 1589 * the following conditions: 1590 * <ul> 1591 * <li>if the field is declared {@code final}, then the write, atomic 1592 * update, and numeric atomic update access modes are unsupported. 1593 * <li>if the field type is anything other than {@code int}, 1594 * {@code long} or a reference type, then atomic update access modes 1595 * are unsupported. (Future major platform releases of the JDK may 1596 * support additional types for certain currently unsupported access 1597 * modes.) 1598 * <li>if the field type is anything other than {@code int} or 1599 * {@code long}, then numeric atomic update access modes are 1600 * unsupported. (Future major platform releases of the JDK may 1601 * support additional numeric types for certain currently 1602 * unsupported access modes.) 1603 * </ul> 1604 * <p> 1605 * If the field is declared {@code volatile} then the returned VarHandle 1606 * will override access to the field (effectively ignore the 1607 * {@code volatile} declaration) in accordance to it's specified 1608 * access modes. 1609 * @param f the reflected field, with a field of type {@code T}, and 1610 * a declaring class of type {@code R} 1611 * @return a VarHandle giving access to non-static fields or a static 1612 * field 1613 * @throws IllegalAccessException if access checking fails 1614 * @throws NullPointerException if the argument is null 1615 * @since 9 1616 */ 1617 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 1618 MemberName getField = new MemberName(f, false); 1619 MemberName putField = new MemberName(f, true); 1620 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 1621 f.getDeclaringClass(), getField, putField); 1622 } 1623 1624 /** 1625 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1626 * created by this lookup object or a similar one. 1627 * Security and access checks are performed to ensure that this lookup object 1628 * is capable of reproducing the target method handle. 1629 * This means that the cracking may fail if target is a direct method handle 1630 * but was created by an unrelated lookup object. 1631 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 1632 * and was created by a lookup object for a different class. 1633 * @param target a direct method handle to crack into symbolic reference components 1634 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 1635 * @exception SecurityException if a security manager is present and it 1636 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1637 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 1638 * @exception NullPointerException if the target is {@code null} 1639 * @see MethodHandleInfo 1640 * @since 1.8 1641 */ 1642 public MethodHandleInfo revealDirect(MethodHandle target) { 1643 MemberName member = target.internalMemberName(); 1644 if (member == null || (!member.isResolved() && 1645 !member.isMethodHandleInvoke() && 1646 !member.isVarHandleMethodInvoke())) 1647 throw newIllegalArgumentException("not a direct method handle"); 1648 Class<?> defc = member.getDeclaringClass(); 1649 byte refKind = member.getReferenceKind(); 1650 assert(MethodHandleNatives.refKindIsValid(refKind)); 1651 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 1652 // Devirtualized method invocation is usually formally virtual. 1653 // To avoid creating extra MemberName objects for this common case, 1654 // we encode this extra degree of freedom using MH.isInvokeSpecial. 1655 refKind = REF_invokeVirtual; 1656 if (refKind == REF_invokeVirtual && defc.isInterface()) 1657 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 1658 refKind = REF_invokeInterface; 1659 // Check SM permissions and member access before cracking. 1660 try { 1661 checkAccess(refKind, defc, member); 1662 checkSecurityManager(defc, member); 1663 } catch (IllegalAccessException ex) { 1664 throw new IllegalArgumentException(ex); 1665 } 1666 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 1667 Class<?> callerClass = target.internalCallerClass(); 1668 if (!hasPrivateAccess() || callerClass != lookupClass()) 1669 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 1670 } 1671 // Produce the handle to the results. 1672 return new InfoFromMemberName(this, member, refKind); 1673 } 1674 1675 /// Helper methods, all package-private. 1676 1677 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1678 checkSymbolicClass(refc); // do this before attempting to resolve 1679 Objects.requireNonNull(name); 1680 Objects.requireNonNull(type); 1681 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1682 NoSuchFieldException.class); 1683 } 1684 1685 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1686 checkSymbolicClass(refc); // do this before attempting to resolve 1687 Objects.requireNonNull(name); 1688 Objects.requireNonNull(type); 1689 checkMethodName(refKind, name); // NPE check on name 1690 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1691 NoSuchMethodException.class); 1692 } 1693 1694 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 1695 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 1696 Objects.requireNonNull(member.getName()); 1697 Objects.requireNonNull(member.getType()); 1698 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), 1699 ReflectiveOperationException.class); 1700 } 1701 1702 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 1703 Objects.requireNonNull(refc); 1704 Class<?> caller = lookupClassOrNull(); 1705 if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes)) 1706 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 1707 } 1708 1709 /** Check name for an illegal leading "<" character. */ 1710 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 1711 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 1712 throw new NoSuchMethodException("illegal method name: "+name); 1713 } 1714 1715 1716 /** 1717 * Find my trustable caller class if m is a caller sensitive method. 1718 * If this lookup object has private access, then the caller class is the lookupClass. 1719 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 1720 */ 1721 Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException { 1722 Class<?> callerClass = null; 1723 if (MethodHandleNatives.isCallerSensitive(m)) { 1724 // Only lookups with private access are allowed to resolve caller-sensitive methods 1725 if (hasPrivateAccess()) { 1726 callerClass = lookupClass; 1727 } else { 1728 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 1729 } 1730 } 1731 return callerClass; 1732 } 1733 1734 private boolean hasPrivateAccess() { 1735 return (allowedModes & PRIVATE) != 0; 1736 } 1737 1738 /** 1739 * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 1740 * Determines a trustable caller class to compare with refc, the symbolic reference class. 1741 * If this lookup object has private access, then the caller class is the lookupClass. 1742 */ 1743 void checkSecurityManager(Class<?> refc, MemberName m) { 1744 SecurityManager smgr = System.getSecurityManager(); 1745 if (smgr == null) return; 1746 if (allowedModes == TRUSTED) return; 1747 1748 // Step 1: 1749 boolean fullPowerLookup = hasPrivateAccess(); 1750 if (!fullPowerLookup || 1751 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 1752 ReflectUtil.checkPackageAccess(refc); 1753 } 1754 1755 if (m == null) { // findClass or accessClass 1756 // Step 2b: 1757 if (!fullPowerLookup) { 1758 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 1759 } 1760 return; 1761 } 1762 1763 // Step 2a: 1764 if (m.isPublic()) return; 1765 if (!fullPowerLookup) { 1766 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 1767 } 1768 1769 // Step 3: 1770 Class<?> defc = m.getDeclaringClass(); 1771 if (!fullPowerLookup && defc != refc) { 1772 ReflectUtil.checkPackageAccess(defc); 1773 } 1774 } 1775 1776 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1777 boolean wantStatic = (refKind == REF_invokeStatic); 1778 String message; 1779 if (m.isConstructor()) 1780 message = "expected a method, not a constructor"; 1781 else if (!m.isMethod()) 1782 message = "expected a method"; 1783 else if (wantStatic != m.isStatic()) 1784 message = wantStatic ? "expected a static method" : "expected a non-static method"; 1785 else 1786 { checkAccess(refKind, refc, m); return; } 1787 throw m.makeAccessException(message, this); 1788 } 1789 1790 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1791 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 1792 String message; 1793 if (wantStatic != m.isStatic()) 1794 message = wantStatic ? "expected a static field" : "expected a non-static field"; 1795 else 1796 { checkAccess(refKind, refc, m); return; } 1797 throw m.makeAccessException(message, this); 1798 } 1799 1800 /** Check public/protected/private bits on the symbolic reference class and its member. */ 1801 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1802 assert(m.referenceKindIsConsistentWith(refKind) && 1803 MethodHandleNatives.refKindIsValid(refKind) && 1804 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 1805 int allowedModes = this.allowedModes; 1806 if (allowedModes == TRUSTED) return; 1807 int mods = m.getModifiers(); 1808 if (Modifier.isProtected(mods) && 1809 refKind == REF_invokeVirtual && 1810 m.getDeclaringClass() == Object.class && 1811 m.getName().equals("clone") && 1812 refc.isArray()) { 1813 // The JVM does this hack also. 1814 // (See ClassVerifier::verify_invoke_instructions 1815 // and LinkResolver::check_method_accessability.) 1816 // Because the JVM does not allow separate methods on array types, 1817 // there is no separate method for int[].clone. 1818 // All arrays simply inherit Object.clone. 1819 // But for access checking logic, we make Object.clone 1820 // (normally protected) appear to be public. 1821 // Later on, when the DirectMethodHandle is created, 1822 // its leading argument will be restricted to the 1823 // requested array type. 1824 // N.B. The return type is not adjusted, because 1825 // that is *not* the bytecode behavior. 1826 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 1827 } 1828 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 1829 // cannot "new" a protected ctor in a different package 1830 mods ^= Modifier.PROTECTED; 1831 } 1832 if (Modifier.isFinal(mods) && 1833 MethodHandleNatives.refKindIsSetter(refKind)) 1834 throw m.makeAccessException("unexpected set of a final field", this); 1835 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 1836 if ((requestedModes & allowedModes) != 0) { 1837 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 1838 mods, lookupClass(), allowedModes)) 1839 return; 1840 } else { 1841 // Protected members can also be checked as if they were package-private. 1842 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 1843 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 1844 return; 1845 } 1846 throw m.makeAccessException(accessFailedMessage(refc, m), this); 1847 } 1848 1849 String accessFailedMessage(Class<?> refc, MemberName m) { 1850 Class<?> defc = m.getDeclaringClass(); 1851 int mods = m.getModifiers(); 1852 // check the class first: 1853 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 1854 (defc == refc || 1855 Modifier.isPublic(refc.getModifiers()))); 1856 if (!classOK && (allowedModes & PACKAGE) != 0) { 1857 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) && 1858 (defc == refc || 1859 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES))); 1860 } 1861 if (!classOK) 1862 return "class is not public"; 1863 if (Modifier.isPublic(mods)) 1864 return "access to public member failed"; // (how?, module not readable?) 1865 if (Modifier.isPrivate(mods)) 1866 return "member is private"; 1867 if (Modifier.isProtected(mods)) 1868 return "member is protected"; 1869 return "member is private to package"; 1870 } 1871 1872 private static final boolean ALLOW_NESTMATE_ACCESS = false; 1873 1874 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 1875 int allowedModes = this.allowedModes; 1876 if (allowedModes == TRUSTED) return; 1877 if (!hasPrivateAccess() 1878 || (specialCaller != lookupClass() 1879 // ensure non-abstract methods in superinterfaces can be special-invoked 1880 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)) 1881 && !(ALLOW_NESTMATE_ACCESS && 1882 VerifyAccess.isSamePackageMember(specialCaller, lookupClass())))) 1883 throw new MemberName(specialCaller). 1884 makeAccessException("no private access for invokespecial", this); 1885 } 1886 1887 private boolean restrictProtectedReceiver(MemberName method) { 1888 // The accessing class only has the right to use a protected member 1889 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 1890 if (!method.isProtected() || method.isStatic() 1891 || allowedModes == TRUSTED 1892 || method.getDeclaringClass() == lookupClass() 1893 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()) 1894 || (ALLOW_NESTMATE_ACCESS && 1895 VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass()))) 1896 return false; 1897 return true; 1898 } 1899 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 1900 assert(!method.isStatic()); 1901 // receiver type of mh is too wide; narrow to caller 1902 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 1903 throw method.makeAccessException("caller class must be a subclass below the method", caller); 1904 } 1905 MethodType rawType = mh.type(); 1906 if (rawType.parameterType(0) == caller) return mh; 1907 MethodType narrowType = rawType.changeParameterType(0, caller); 1908 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 1909 assert(mh.viewAsTypeChecks(narrowType, true)); 1910 return mh.copyWith(narrowType, mh.form); 1911 } 1912 1913 /** Check access and get the requested method. */ 1914 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1915 final boolean doRestrict = true; 1916 final boolean checkSecurity = true; 1917 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1918 } 1919 /** Check access and get the requested method, eliding receiver narrowing rules. */ 1920 private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1921 final boolean doRestrict = false; 1922 final boolean checkSecurity = true; 1923 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1924 } 1925 /** Check access and get the requested method, eliding security manager checks. */ 1926 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1927 final boolean doRestrict = true; 1928 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 1929 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1930 } 1931 /** Common code for all methods; do not call directly except from immediately above. */ 1932 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 1933 boolean checkSecurity, 1934 boolean doRestrict, Class<?> callerClass) throws IllegalAccessException { 1935 checkMethod(refKind, refc, method); 1936 // Optionally check with the security manager; this isn't needed for unreflect* calls. 1937 if (checkSecurity) 1938 checkSecurityManager(refc, method); 1939 assert(!method.isMethodHandleInvoke()); 1940 1941 if (refKind == REF_invokeSpecial && 1942 refc != lookupClass() && 1943 !refc.isInterface() && 1944 refc != lookupClass().getSuperclass() && 1945 refc.isAssignableFrom(lookupClass())) { 1946 assert(!method.getName().equals("<init>")); // not this code path 1947 // Per JVMS 6.5, desc. of invokespecial instruction: 1948 // If the method is in a superclass of the LC, 1949 // and if our original search was above LC.super, 1950 // repeat the search (symbolic lookup) from LC.super 1951 // and continue with the direct superclass of that class, 1952 // and so forth, until a match is found or no further superclasses exist. 1953 // FIXME: MemberName.resolve should handle this instead. 1954 Class<?> refcAsSuper = lookupClass(); 1955 MemberName m2; 1956 do { 1957 refcAsSuper = refcAsSuper.getSuperclass(); 1958 m2 = new MemberName(refcAsSuper, 1959 method.getName(), 1960 method.getMethodType(), 1961 REF_invokeSpecial); 1962 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); 1963 } while (m2 == null && // no method is found yet 1964 refc != refcAsSuper); // search up to refc 1965 if (m2 == null) throw new InternalError(method.toString()); 1966 method = m2; 1967 refc = refcAsSuper; 1968 // redo basic checks 1969 checkMethod(refKind, refc, method); 1970 } 1971 1972 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method); 1973 MethodHandle mh = dmh; 1974 // Optionally narrow the receiver argument to refc using restrictReceiver. 1975 if (doRestrict && 1976 (refKind == REF_invokeSpecial || 1977 (MethodHandleNatives.refKindHasReceiver(refKind) && 1978 restrictProtectedReceiver(method)))) { 1979 mh = restrictReceiver(method, dmh, lookupClass()); 1980 } 1981 mh = maybeBindCaller(method, mh, callerClass); 1982 mh = mh.setVarargs(method); 1983 return mh; 1984 } 1985 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, 1986 Class<?> callerClass) 1987 throws IllegalAccessException { 1988 if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 1989 return mh; 1990 Class<?> hostClass = lookupClass; 1991 if (!hasPrivateAccess()) // caller must have private access 1992 hostClass = callerClass; // callerClass came from a security manager style stack walk 1993 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); 1994 // Note: caller will apply varargs after this step happens. 1995 return cbmh; 1996 } 1997 /** Check access and get the requested field. */ 1998 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 1999 final boolean checkSecurity = true; 2000 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2001 } 2002 /** Check access and get the requested field, eliding security manager checks. */ 2003 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 2004 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2005 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2006 } 2007 /** Common code for all fields; do not call directly except from immediately above. */ 2008 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 2009 boolean checkSecurity) throws IllegalAccessException { 2010 checkField(refKind, refc, field); 2011 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2012 if (checkSecurity) 2013 checkSecurityManager(refc, field); 2014 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 2015 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 2016 restrictProtectedReceiver(field)); 2017 if (doRestrict) 2018 return restrictReceiver(field, dmh, lookupClass()); 2019 return dmh; 2020 } 2021 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 2022 Class<?> refc, MemberName getField, MemberName putField) 2023 throws IllegalAccessException { 2024 final boolean checkSecurity = true; 2025 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2026 } 2027 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 2028 Class<?> refc, MemberName getField, MemberName putField) 2029 throws IllegalAccessException { 2030 final boolean checkSecurity = false; 2031 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2032 } 2033 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 2034 Class<?> refc, MemberName getField, MemberName putField, 2035 boolean checkSecurity) throws IllegalAccessException { 2036 assert getField.isStatic() == putField.isStatic(); 2037 assert getField.isGetter() && putField.isSetter(); 2038 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 2039 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 2040 2041 checkField(getRefKind, refc, getField); 2042 if (checkSecurity) 2043 checkSecurityManager(refc, getField); 2044 2045 if (!putField.isFinal()) { 2046 // A VarHandle does not support updates to final fields, any 2047 // such VarHandle to a final field will be read-only and 2048 // therefore the following write-based accessibility checks are 2049 // only required for non-final fields 2050 checkField(putRefKind, refc, putField); 2051 if (checkSecurity) 2052 checkSecurityManager(refc, putField); 2053 } 2054 2055 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 2056 restrictProtectedReceiver(getField)); 2057 if (doRestrict) { 2058 assert !getField.isStatic(); 2059 // receiver type of VarHandle is too wide; narrow to caller 2060 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 2061 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 2062 } 2063 refc = lookupClass(); 2064 } 2065 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED); 2066 } 2067 /** Check access and get the requested constructor. */ 2068 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2069 final boolean checkSecurity = true; 2070 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2071 } 2072 /** Check access and get the requested constructor, eliding security manager checks. */ 2073 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2074 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2075 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2076 } 2077 /** Common code for all constructors; do not call directly except from immediately above. */ 2078 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 2079 boolean checkSecurity) throws IllegalAccessException { 2080 assert(ctor.isConstructor()); 2081 checkAccess(REF_newInvokeSpecial, refc, ctor); 2082 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2083 if (checkSecurity) 2084 checkSecurityManager(refc, ctor); 2085 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 2086 return DirectMethodHandle.make(ctor).setVarargs(ctor); 2087 } 2088 2089 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 2090 */ 2091 /*non-public*/ 2092 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { 2093 if (!(type instanceof Class || type instanceof MethodType)) 2094 throw new InternalError("unresolved MemberName"); 2095 MemberName member = new MemberName(refKind, defc, name, type); 2096 MethodHandle mh = LOOKASIDE_TABLE.get(member); 2097 if (mh != null) { 2098 checkSymbolicClass(defc); 2099 return mh; 2100 } 2101 // Treat MethodHandle.invoke and invokeExact specially. 2102 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 2103 mh = findVirtualForMH(member.getName(), member.getMethodType()); 2104 if (mh != null) { 2105 return mh; 2106 } 2107 } 2108 MemberName resolved = resolveOrFail(refKind, member); 2109 mh = getDirectMethodForConstant(refKind, defc, resolved); 2110 if (mh instanceof DirectMethodHandle 2111 && canBeCached(refKind, defc, resolved)) { 2112 MemberName key = mh.internalMemberName(); 2113 if (key != null) { 2114 key = key.asNormalOriginal(); 2115 } 2116 if (member.equals(key)) { // better safe than sorry 2117 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 2118 } 2119 } 2120 return mh; 2121 } 2122 private 2123 boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 2124 if (refKind == REF_invokeSpecial) { 2125 return false; 2126 } 2127 if (!Modifier.isPublic(defc.getModifiers()) || 2128 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 2129 !member.isPublic() || 2130 member.isCallerSensitive()) { 2131 return false; 2132 } 2133 ClassLoader loader = defc.getClassLoader(); 2134 if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) { 2135 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 2136 boolean found = false; 2137 while (sysl != null) { 2138 if (loader == sysl) { found = true; break; } 2139 sysl = sysl.getParent(); 2140 } 2141 if (!found) { 2142 return false; 2143 } 2144 } 2145 try { 2146 MemberName resolved2 = publicLookup().resolveOrFail(refKind, 2147 new MemberName(refKind, defc, member.getName(), member.getType())); 2148 checkSecurityManager(defc, resolved2); 2149 } catch (ReflectiveOperationException | SecurityException ex) { 2150 return false; 2151 } 2152 return true; 2153 } 2154 private 2155 MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 2156 throws ReflectiveOperationException { 2157 if (MethodHandleNatives.refKindIsField(refKind)) { 2158 return getDirectFieldNoSecurityManager(refKind, defc, member); 2159 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 2160 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); 2161 } else if (refKind == REF_newInvokeSpecial) { 2162 return getDirectConstructorNoSecurityManager(defc, member); 2163 } 2164 // oops 2165 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 2166 } 2167 2168 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 2169 } 2170 2171 /** 2172 * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class 2173 * in an <em>unnamed module</em>. 2174 * 2175 * @see Lookup#publicLookup 2176 */ 2177 private static class LookupHelper { 2178 private static final String UNNAMED = "Unnamed"; 2179 private static final String OBJECT = "java/lang/Object"; 2180 2181 private static Class<?> createClass() { 2182 try { 2183 ClassWriter cw = new ClassWriter(0); 2184 cw.visit(Opcodes.V1_8, 2185 Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, 2186 UNNAMED, 2187 null, 2188 OBJECT, 2189 null); 2190 cw.visitSource(UNNAMED, null); 2191 cw.visitEnd(); 2192 byte[] bytes = cw.toByteArray(); 2193 ClassLoader loader = new ClassLoader(null) { 2194 @Override 2195 protected Class<?> findClass(String cn) throws ClassNotFoundException { 2196 if (cn.equals(UNNAMED)) 2197 return super.defineClass(UNNAMED, bytes, 0, bytes.length); 2198 throw new ClassNotFoundException(cn); 2199 } 2200 }; 2201 return loader.loadClass(UNNAMED); 2202 } catch (Exception e) { 2203 throw new InternalError(e); 2204 } 2205 } 2206 2207 private static final Class<?> PUBLIC_LOOKUP_CLASS; 2208 static { 2209 PrivilegedAction<Class<?>> pa = new PrivilegedAction<Class<?>>() { 2210 public Class<?> run() { 2211 return createClass(); 2212 } 2213 }; 2214 PUBLIC_LOOKUP_CLASS = AccessController.doPrivileged(pa); 2215 } 2216 2217 /** 2218 * Lookup that is trusted minimally. It can only be used to create 2219 * method handles to publicly accessible members in exported packages. 2220 * 2221 * @see MethodHandles#publicLookup 2222 */ 2223 static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC); 2224 } 2225 2226 /** 2227 * Produces a method handle that can construct arrays of a desired type. 2228 * The return type of the method handle will be the array type. 2229 * The type of its sole argument will be {@code int}, which specifies the size of the array. 2230 * @param arrayClass an array type 2231 * @return a method handle which can create arrays of the given type 2232 * @throws NullPointerException if the argument is {@code null} 2233 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 2234 * @since 9 2235 */ 2236 public static 2237 MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 2238 if (!arrayClass.isArray()) { 2239 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 2240 } 2241 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 2242 bindTo(arrayClass.getComponentType()); 2243 return ani.asType(ani.type().changeReturnType(arrayClass)); 2244 } 2245 2246 /** 2247 * Produces a method handle giving read access to elements of an array. 2248 * The type of the method handle will have a return type of the array's 2249 * element type. Its first argument will be the array type, 2250 * and the second will be {@code int}. 2251 * @param arrayClass an array type 2252 * @return a method handle which can load values from the given array type 2253 * @throws NullPointerException if the argument is null 2254 * @throws IllegalArgumentException if arrayClass is not an array type 2255 */ 2256 public static 2257 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 2258 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false); 2259 } 2260 2261 /** 2262 * Produces a method handle giving write access to elements of an array. 2263 * The type of the method handle will have a void return type. 2264 * Its last argument will be the array's element type. 2265 * The first and second arguments will be the array type and int. 2266 * @param arrayClass the class of an array 2267 * @return a method handle which can store values into the array type 2268 * @throws NullPointerException if the argument is null 2269 * @throws IllegalArgumentException if arrayClass is not an array type 2270 */ 2271 public static 2272 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 2273 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true); 2274 } 2275 2276 /** 2277 * 2278 * Produces a VarHandle giving access to elements of an array type 2279 * {@code T[]}, supporting shape {@code (T[], int : T)}. 2280 * <p> 2281 * Certain access modes of the returned VarHandle are unsupported under 2282 * the following conditions: 2283 * <ul> 2284 * <li>if the component type is anything other than {@code int}, 2285 * {@code long} or a reference type, then atomic update access modes 2286 * are unsupported. (Future major platform releases of the JDK may 2287 * support additional types for certain currently unsupported access 2288 * modes.) 2289 * <li>if the component type is anything other than {@code int} or 2290 * {@code long}, then numeric atomic update access modes are 2291 * unsupported. (Future major platform releases of the JDK may 2292 * support additional numeric types for certain currently 2293 * unsupported access modes.) 2294 * </ul> 2295 * @param arrayClass the class of an array, of type {@code T[]} 2296 * @return a VarHandle giving access to elements of an array 2297 * @throws NullPointerException if the arrayClass is null 2298 * @throws IllegalArgumentException if arrayClass is not an array type 2299 * @since 9 2300 */ 2301 public static 2302 VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 2303 return VarHandles.makeArrayElementHandle(arrayClass); 2304 } 2305 2306 /** 2307 * Produces a VarHandle giving access to elements of a {@code byte[]} array 2308 * viewed as if it were a different primitive array type, such as 2309 * {@code int[]} or {@code long[]}. The shape of the resulting VarHandle is 2310 * {@code (byte[], int : T)}, where the {@code int} coordinate type 2311 * corresponds to an argument that is an index in a {@code byte[]} array, 2312 * and {@code T} is the component type of the given view array class. The 2313 * returned VarHandle accesses bytes at an index in a {@code byte[]} array, 2314 * composing bytes to or from a value of {@code T} according to the given 2315 * endianness. 2316 * <p> 2317 * The supported component types (variables types) are {@code short}, 2318 * {@code char}, {@code int}, {@code long}, {@code float} and 2319 * {@code double}. 2320 * <p> 2321 * Access of bytes at a given index will result in an 2322 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2323 * or greater than the {@code byte[]} array length minus the size (in bytes) 2324 * of {@code T}. 2325 * <p> 2326 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2327 * with respect to the underlying memory address, {@code A} say, associated 2328 * with the array and index. 2329 * If access is misaligned then access for anything other than the 2330 * {@code get} and {@code set} access modes will result in an 2331 * {@code IllegalStateException}. In such cases atomic access is only 2332 * guaranteed with respect to the largest power of two that divides the GCD 2333 * of {@code A} and the size (in bytes) of {@code T}. 2334 * If access is aligned then following access modes are supported and are 2335 * guaranteed to support atomic access: 2336 * <ul> 2337 * <li>read write access modes for all {@code T}; 2338 * <li>atomic update access modes for {@code int}, {@code long}, 2339 * {@code float} or {@code double}. 2340 * (Future major platform releases of the JDK may support additional 2341 * types for certain currently unsupported access modes.) 2342 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2343 * (Future major platform releases of the JDK may support additional 2344 * numeric types for certain currently unsupported access modes.) 2345 * </ul> 2346 * <p> 2347 * Misaligned access, and therefore atomicity guarantees, may be determined 2348 * for {@code byte[]} arrays without operating on a specific array. Given 2349 * an {@code index}, {@code T} and it's corresponding boxed type, 2350 * {@code T_BOX}, misalignment may be determined as follows: 2351 * <pre>{@code 2352 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2353 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 2354 * alignmentOffset(0, sizeOfT); 2355 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 2356 * boolean isMisaligned = misalignedAtIndex != 0; 2357 * }</pre> 2358 * 2359 * @implNote 2360 * The variable types {@code float} and {@code double} are supported as if 2361 * by transformation to and access with the variable types {@code int} and 2362 * {@code long} respectively. For example, the transformation of a 2363 * {@code double} value to a long value is performed as if using 2364 * {@link Double#doubleToRawLongBits(double)}, and the reverse 2365 * transformation is performed as if using 2366 * {@link Double#longBitsToDouble(long)}. 2367 * 2368 * @param viewArrayClass the view array class, with a component type of 2369 * type {@code T} 2370 * @param byteOrder the endianness of the view array elements, as 2371 * stored in the underlying {@code byte} array 2372 * @return a VarHandle giving access to elements of a {@code byte[]} array 2373 * viewed as if elements corresponding to the components type of the view 2374 * array class 2375 * @throws NullPointerException if viewArrayClass or byteOrder is null 2376 * @throws IllegalArgumentException if viewArrayClass is not an array type 2377 * @throws UnsupportedOperationException if the component type of 2378 * viewArrayClass is not supported as a variable type 2379 * @since 9 2380 */ 2381 public static 2382 VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 2383 ByteOrder byteOrder) throws IllegalArgumentException { 2384 Objects.requireNonNull(byteOrder); 2385 return VarHandles.byteArrayViewHandle(viewArrayClass, 2386 byteOrder == ByteOrder.BIG_ENDIAN); 2387 } 2388 2389 /** 2390 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 2391 * viewed as if it were an array of elements of a different primitive 2392 * component type to that of {@code byte}, such as {@code int[]} or 2393 * {@code long[]}. The shape of the resulting VarHandle is 2394 * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type 2395 * corresponds to an argument that is an index in a {@code ByteBuffer}, and 2396 * {@code T} is the component type of the given view array class. The 2397 * returned VarHandle accesses bytes at an index in a {@code ByteBuffer}, 2398 * composing bytes to or from a value of {@code T} according to the given 2399 * endianness. 2400 * <p> 2401 * The supported component types (variables types) are {@code short}, 2402 * {@code char}, {@code int}, {@code long}, {@code float} and 2403 * {@code double}. 2404 * <p> 2405 * Access will result in a {@code ReadOnlyBufferException} for anything 2406 * other than the read access modes if the {@code ByteBuffer} is read-only. 2407 * <p> 2408 * Access of bytes at a given index will result in an 2409 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2410 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 2411 * {@code T}. 2412 * <p> 2413 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2414 * with respect to the underlying memory address, {@code A} say, associated 2415 * with the {@code ByteBuffer} and index. 2416 * If access is misaligned then access for anything other than the 2417 * {@code get} and {@code set} access modes will result in an 2418 * {@code IllegalStateException}. In such cases atomic access is only 2419 * guaranteed with respect to the largest power of two that divides the GCD 2420 * of {@code A} and the size (in bytes) of {@code T}. 2421 * If access is aligned then following access modes are supported and are 2422 * guaranteed to support atomic access: 2423 * <ul> 2424 * <li>read write access modes for all {@code T}; 2425 * <li>atomic update access modes for {@code int}, {@code long}, 2426 * {@code float} or {@code double}. 2427 * (Future major platform releases of the JDK may support additional 2428 * types for certain currently unsupported access modes.) 2429 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2430 * (Future major platform releases of the JDK may support additional 2431 * numeric types for certain currently unsupported access modes.) 2432 * </ul> 2433 * <p> 2434 * Misaligned access, and therefore atomicity guarantees, may be determined 2435 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 2436 * {@code index}, {@code T} and it's corresponding boxed type, 2437 * {@code T_BOX}, as follows: 2438 * <pre>{@code 2439 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2440 * ByteBuffer bb = ... 2441 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 2442 * boolean isMisaligned = misalignedAtIndex != 0; 2443 * }</pre> 2444 * 2445 * @implNote 2446 * The variable types {@code float} and {@code double} are supported as if 2447 * by transformation to and access with the variable types {@code int} and 2448 * {@code long} respectively. For example, the transformation of a 2449 * {@code double} value to a long value is performed as if using 2450 * {@link Double#doubleToRawLongBits(double)}, and the reverse 2451 * transformation is performed as if using 2452 * {@link Double#longBitsToDouble(long)}. 2453 * 2454 * @param viewArrayClass the view array class, with a component type of 2455 * type {@code T} 2456 * @param byteOrder the endianness of the view array elements, as 2457 * stored in the underlying {@code ByteBuffer} (Note this overrides the 2458 * endianness of a {@code ByteBuffer}) 2459 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 2460 * viewed as if elements corresponding to the components type of the view 2461 * array class 2462 * @throws NullPointerException if viewArrayClass or byteOrder is null 2463 * @throws IllegalArgumentException if viewArrayClass is not an array type 2464 * @throws UnsupportedOperationException if the component type of 2465 * viewArrayClass is not supported as a variable type 2466 * @since 9 2467 */ 2468 public static 2469 VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 2470 ByteOrder byteOrder) throws IllegalArgumentException { 2471 Objects.requireNonNull(byteOrder); 2472 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 2473 byteOrder == ByteOrder.BIG_ENDIAN); 2474 } 2475 2476 2477 /// method handle invocation (reflective style) 2478 2479 /** 2480 * Produces a method handle which will invoke any method handle of the 2481 * given {@code type}, with a given number of trailing arguments replaced by 2482 * a single trailing {@code Object[]} array. 2483 * The resulting invoker will be a method handle with the following 2484 * arguments: 2485 * <ul> 2486 * <li>a single {@code MethodHandle} target 2487 * <li>zero or more leading values (counted by {@code leadingArgCount}) 2488 * <li>an {@code Object[]} array containing trailing arguments 2489 * </ul> 2490 * <p> 2491 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 2492 * the indicated {@code type}. 2493 * That is, if the target is exactly of the given {@code type}, it will behave 2494 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 2495 * is used to convert the target to the required {@code type}. 2496 * <p> 2497 * The type of the returned invoker will not be the given {@code type}, but rather 2498 * will have all parameters except the first {@code leadingArgCount} 2499 * replaced by a single array of type {@code Object[]}, which will be 2500 * the final parameter. 2501 * <p> 2502 * Before invoking its target, the invoker will spread the final array, apply 2503 * reference casts as necessary, and unbox and widen primitive arguments. 2504 * If, when the invoker is called, the supplied array argument does 2505 * not have the correct number of elements, the invoker will throw 2506 * an {@link IllegalArgumentException} instead of invoking the target. 2507 * <p> 2508 * This method is equivalent to the following code (though it may be more efficient): 2509 * <blockquote><pre>{@code 2510 MethodHandle invoker = MethodHandles.invoker(type); 2511 int spreadArgCount = type.parameterCount() - leadingArgCount; 2512 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 2513 return invoker; 2514 * }</pre></blockquote> 2515 * This method throws no reflective or security exceptions. 2516 * @param type the desired target type 2517 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 2518 * @return a method handle suitable for invoking any method handle of the given type 2519 * @throws NullPointerException if {@code type} is null 2520 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 2521 * the range from 0 to {@code type.parameterCount()} inclusive, 2522 * or if the resulting method handle's type would have 2523 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2524 */ 2525 public static 2526 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 2527 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 2528 throw newIllegalArgumentException("bad argument count", leadingArgCount); 2529 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 2530 return type.invokers().spreadInvoker(leadingArgCount); 2531 } 2532 2533 /** 2534 * Produces a special <em>invoker method handle</em> which can be used to 2535 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 2536 * The resulting invoker will have a type which is 2537 * exactly equal to the desired type, except that it will accept 2538 * an additional leading argument of type {@code MethodHandle}. 2539 * <p> 2540 * This method is equivalent to the following code (though it may be more efficient): 2541 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 2542 * 2543 * <p style="font-size:smaller;"> 2544 * <em>Discussion:</em> 2545 * Invoker method handles can be useful when working with variable method handles 2546 * of unknown types. 2547 * For example, to emulate an {@code invokeExact} call to a variable method 2548 * handle {@code M}, extract its type {@code T}, 2549 * look up the invoker method {@code X} for {@code T}, 2550 * and call the invoker method, as {@code X.invoke(T, A...)}. 2551 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 2552 * is unknown.) 2553 * If spreading, collecting, or other argument transformations are required, 2554 * they can be applied once to the invoker {@code X} and reused on many {@code M} 2555 * method handle values, as long as they are compatible with the type of {@code X}. 2556 * <p style="font-size:smaller;"> 2557 * <em>(Note: The invoker method is not available via the Core Reflection API. 2558 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2559 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2560 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2561 * <p> 2562 * This method throws no reflective or security exceptions. 2563 * @param type the desired target type 2564 * @return a method handle suitable for invoking any method handle of the given type 2565 * @throws IllegalArgumentException if the resulting method handle's type would have 2566 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2567 */ 2568 public static 2569 MethodHandle exactInvoker(MethodType type) { 2570 return type.invokers().exactInvoker(); 2571 } 2572 2573 /** 2574 * Produces a special <em>invoker method handle</em> which can be used to 2575 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 2576 * The resulting invoker will have a type which is 2577 * exactly equal to the desired type, except that it will accept 2578 * an additional leading argument of type {@code MethodHandle}. 2579 * <p> 2580 * Before invoking its target, if the target differs from the expected type, 2581 * the invoker will apply reference casts as 2582 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 2583 * Similarly, the return value will be converted as necessary. 2584 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 2585 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 2586 * <p> 2587 * This method is equivalent to the following code (though it may be more efficient): 2588 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 2589 * <p style="font-size:smaller;"> 2590 * <em>Discussion:</em> 2591 * A {@linkplain MethodType#genericMethodType general method type} is one which 2592 * mentions only {@code Object} arguments and return values. 2593 * An invoker for such a type is capable of calling any method handle 2594 * of the same arity as the general type. 2595 * <p style="font-size:smaller;"> 2596 * <em>(Note: The invoker method is not available via the Core Reflection API. 2597 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2598 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2599 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2600 * <p> 2601 * This method throws no reflective or security exceptions. 2602 * @param type the desired target type 2603 * @return a method handle suitable for invoking any method handle convertible to the given type 2604 * @throws IllegalArgumentException if the resulting method handle's type would have 2605 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2606 */ 2607 public static 2608 MethodHandle invoker(MethodType type) { 2609 return type.invokers().genericInvoker(); 2610 } 2611 2612 /** 2613 * Produces a special <em>invoker method handle</em> which can be used to 2614 * invoke a signature-polymorphic access mode method on any VarHandle whose 2615 * associated access mode type is compatible with the given type. 2616 * The resulting invoker will have a type which is exactly equal to the 2617 * desired given type, except that it will accept an additional leading 2618 * argument of type {@code VarHandle}. 2619 * 2620 * @param accessMode the VarHandle access mode 2621 * @param type the desired target type 2622 * @return a method handle suitable for invoking an access mode method of 2623 * any VarHandle whose access mode type is of the given type. 2624 * @since 9 2625 */ 2626 static public 2627 MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2628 return type.invokers().varHandleMethodExactInvoker(accessMode); 2629 } 2630 2631 /** 2632 * Produces a special <em>invoker method handle</em> which can be used to 2633 * invoke a signature-polymorphic access mode method on any VarHandle whose 2634 * associated access mode type is compatible with the given type. 2635 * The resulting invoker will have a type which is exactly equal to the 2636 * desired given type, except that it will accept an additional leading 2637 * argument of type {@code VarHandle}. 2638 * <p> 2639 * Before invoking its target, if the access mode type differs from the 2640 * desired given type, the invoker will apply reference casts as necessary 2641 * and box, unbox, or widen primitive values, as if by 2642 * {@link MethodHandle#asType asType}. Similarly, the return value will be 2643 * converted as necessary. 2644 * <p> 2645 * This method is equivalent to the following code (though it may be more 2646 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 2647 * 2648 * @param accessMode the VarHandle access mode 2649 * @param type the desired target type 2650 * @return a method handle suitable for invoking an access mode method of 2651 * any VarHandle whose access mode type is convertible to the given 2652 * type. 2653 * @since 9 2654 */ 2655 static public 2656 MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2657 return type.invokers().varHandleMethodInvoker(accessMode); 2658 } 2659 2660 static /*non-public*/ 2661 MethodHandle basicInvoker(MethodType type) { 2662 return type.invokers().basicInvoker(); 2663 } 2664 2665 /// method handle modification (creation from other method handles) 2666 2667 /** 2668 * Produces a method handle which adapts the type of the 2669 * given method handle to a new type by pairwise argument and return type conversion. 2670 * The original type and new type must have the same number of arguments. 2671 * The resulting method handle is guaranteed to report a type 2672 * which is equal to the desired new type. 2673 * <p> 2674 * If the original type and new type are equal, returns target. 2675 * <p> 2676 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 2677 * and some additional conversions are also applied if those conversions fail. 2678 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 2679 * if possible, before or instead of any conversions done by {@code asType}: 2680 * <ul> 2681 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 2682 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 2683 * (This treatment of interfaces follows the usage of the bytecode verifier.) 2684 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 2685 * the boolean is converted to a byte value, 1 for true, 0 for false. 2686 * (This treatment follows the usage of the bytecode verifier.) 2687 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 2688 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 2689 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 2690 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 2691 * then a Java casting conversion (JLS 5.5) is applied. 2692 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 2693 * widening and/or narrowing.) 2694 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 2695 * conversion will be applied at runtime, possibly followed 2696 * by a Java casting conversion (JLS 5.5) on the primitive value, 2697 * possibly followed by a conversion from byte to boolean by testing 2698 * the low-order bit. 2699 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 2700 * and if the reference is null at runtime, a zero value is introduced. 2701 * </ul> 2702 * @param target the method handle to invoke after arguments are retyped 2703 * @param newType the expected type of the new method handle 2704 * @return a method handle which delegates to the target after performing 2705 * any necessary argument conversions, and arranges for any 2706 * necessary return value conversions 2707 * @throws NullPointerException if either argument is null 2708 * @throws WrongMethodTypeException if the conversion cannot be made 2709 * @see MethodHandle#asType 2710 */ 2711 public static 2712 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 2713 explicitCastArgumentsChecks(target, newType); 2714 // use the asTypeCache when possible: 2715 MethodType oldType = target.type(); 2716 if (oldType == newType) return target; 2717 if (oldType.explicitCastEquivalentToAsType(newType)) { 2718 return target.asFixedArity().asType(newType); 2719 } 2720 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 2721 } 2722 2723 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 2724 if (target.type().parameterCount() != newType.parameterCount()) { 2725 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 2726 } 2727 } 2728 2729 /** 2730 * Produces a method handle which adapts the calling sequence of the 2731 * given method handle to a new type, by reordering the arguments. 2732 * The resulting method handle is guaranteed to report a type 2733 * which is equal to the desired new type. 2734 * <p> 2735 * The given array controls the reordering. 2736 * Call {@code #I} the number of incoming parameters (the value 2737 * {@code newType.parameterCount()}, and call {@code #O} the number 2738 * of outgoing parameters (the value {@code target.type().parameterCount()}). 2739 * Then the length of the reordering array must be {@code #O}, 2740 * and each element must be a non-negative number less than {@code #I}. 2741 * For every {@code N} less than {@code #O}, the {@code N}-th 2742 * outgoing argument will be taken from the {@code I}-th incoming 2743 * argument, where {@code I} is {@code reorder[N]}. 2744 * <p> 2745 * No argument or return value conversions are applied. 2746 * The type of each incoming argument, as determined by {@code newType}, 2747 * must be identical to the type of the corresponding outgoing parameter 2748 * or parameters in the target method handle. 2749 * The return type of {@code newType} must be identical to the return 2750 * type of the original target. 2751 * <p> 2752 * The reordering array need not specify an actual permutation. 2753 * An incoming argument will be duplicated if its index appears 2754 * more than once in the array, and an incoming argument will be dropped 2755 * if its index does not appear in the array. 2756 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 2757 * incoming arguments which are not mentioned in the reordering array 2758 * may be of any type, as determined only by {@code newType}. 2759 * <blockquote><pre>{@code 2760 import static java.lang.invoke.MethodHandles.*; 2761 import static java.lang.invoke.MethodType.*; 2762 ... 2763 MethodType intfn1 = methodType(int.class, int.class); 2764 MethodType intfn2 = methodType(int.class, int.class, int.class); 2765 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 2766 assert(sub.type().equals(intfn2)); 2767 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 2768 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 2769 assert((int)rsub.invokeExact(1, 100) == 99); 2770 MethodHandle add = ... (int x, int y) -> (x+y) ...; 2771 assert(add.type().equals(intfn2)); 2772 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 2773 assert(twice.type().equals(intfn1)); 2774 assert((int)twice.invokeExact(21) == 42); 2775 * }</pre></blockquote> 2776 * <p> 2777 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 2778 * variable-arity method handle}, even if the original target method handle was. 2779 * @param target the method handle to invoke after arguments are reordered 2780 * @param newType the expected type of the new method handle 2781 * @param reorder an index array which controls the reordering 2782 * @return a method handle which delegates to the target after it 2783 * drops unused arguments and moves and/or duplicates the other arguments 2784 * @throws NullPointerException if any argument is null 2785 * @throws IllegalArgumentException if the index array length is not equal to 2786 * the arity of the target, or if any index array element 2787 * not a valid index for a parameter of {@code newType}, 2788 * or if two corresponding parameter types in 2789 * {@code target.type()} and {@code newType} are not identical, 2790 */ 2791 public static 2792 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 2793 reorder = reorder.clone(); // get a private copy 2794 MethodType oldType = target.type(); 2795 permuteArgumentChecks(reorder, newType, oldType); 2796 // first detect dropped arguments and handle them separately 2797 int[] originalReorder = reorder; 2798 BoundMethodHandle result = target.rebind(); 2799 LambdaForm form = result.form; 2800 int newArity = newType.parameterCount(); 2801 // Normalize the reordering into a real permutation, 2802 // by removing duplicates and adding dropped elements. 2803 // This somewhat improves lambda form caching, as well 2804 // as simplifying the transform by breaking it up into steps. 2805 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 2806 if (ddIdx > 0) { 2807 // We found a duplicated entry at reorder[ddIdx]. 2808 // Example: (x,y,z)->asList(x,y,z) 2809 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 2810 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 2811 // The starred element corresponds to the argument 2812 // deleted by the dupArgumentForm transform. 2813 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 2814 boolean killFirst = false; 2815 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 2816 // Set killFirst if the dup is larger than an intervening position. 2817 // This will remove at least one inversion from the permutation. 2818 if (dupVal > val) killFirst = true; 2819 } 2820 if (!killFirst) { 2821 srcPos = dstPos; 2822 dstPos = ddIdx; 2823 } 2824 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 2825 assert (reorder[srcPos] == reorder[dstPos]); 2826 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 2827 // contract the reordering by removing the element at dstPos 2828 int tailPos = dstPos + 1; 2829 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 2830 reorder = Arrays.copyOf(reorder, reorder.length - 1); 2831 } else { 2832 int dropVal = ~ddIdx, insPos = 0; 2833 while (insPos < reorder.length && reorder[insPos] < dropVal) { 2834 // Find first element of reorder larger than dropVal. 2835 // This is where we will insert the dropVal. 2836 insPos += 1; 2837 } 2838 Class<?> ptype = newType.parameterType(dropVal); 2839 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 2840 oldType = oldType.insertParameterTypes(insPos, ptype); 2841 // expand the reordering by inserting an element at insPos 2842 int tailPos = insPos + 1; 2843 reorder = Arrays.copyOf(reorder, reorder.length + 1); 2844 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 2845 reorder[insPos] = dropVal; 2846 } 2847 assert (permuteArgumentChecks(reorder, newType, oldType)); 2848 } 2849 assert (reorder.length == newArity); // a perfect permutation 2850 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 2851 form = form.editor().permuteArgumentsForm(1, reorder); 2852 if (newType == result.type() && form == result.internalForm()) 2853 return result; 2854 return result.copyWith(newType, form); 2855 } 2856 2857 /** 2858 * Return an indication of any duplicate or omission in reorder. 2859 * If the reorder contains a duplicate entry, return the index of the second occurrence. 2860 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 2861 * Otherwise, return zero. 2862 * If an element not in [0..newArity-1] is encountered, return reorder.length. 2863 */ 2864 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 2865 final int BIT_LIMIT = 63; // max number of bits in bit mask 2866 if (newArity < BIT_LIMIT) { 2867 long mask = 0; 2868 for (int i = 0; i < reorder.length; i++) { 2869 int arg = reorder[i]; 2870 if (arg >= newArity) { 2871 return reorder.length; 2872 } 2873 long bit = 1L << arg; 2874 if ((mask & bit) != 0) { 2875 return i; // >0 indicates a dup 2876 } 2877 mask |= bit; 2878 } 2879 if (mask == (1L << newArity) - 1) { 2880 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 2881 return 0; 2882 } 2883 // find first zero 2884 long zeroBit = Long.lowestOneBit(~mask); 2885 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 2886 assert(zeroPos <= newArity); 2887 if (zeroPos == newArity) { 2888 return 0; 2889 } 2890 return ~zeroPos; 2891 } else { 2892 // same algorithm, different bit set 2893 BitSet mask = new BitSet(newArity); 2894 for (int i = 0; i < reorder.length; i++) { 2895 int arg = reorder[i]; 2896 if (arg >= newArity) { 2897 return reorder.length; 2898 } 2899 if (mask.get(arg)) { 2900 return i; // >0 indicates a dup 2901 } 2902 mask.set(arg); 2903 } 2904 int zeroPos = mask.nextClearBit(0); 2905 assert(zeroPos <= newArity); 2906 if (zeroPos == newArity) { 2907 return 0; 2908 } 2909 return ~zeroPos; 2910 } 2911 } 2912 2913 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 2914 if (newType.returnType() != oldType.returnType()) 2915 throw newIllegalArgumentException("return types do not match", 2916 oldType, newType); 2917 if (reorder.length == oldType.parameterCount()) { 2918 int limit = newType.parameterCount(); 2919 boolean bad = false; 2920 for (int j = 0; j < reorder.length; j++) { 2921 int i = reorder[j]; 2922 if (i < 0 || i >= limit) { 2923 bad = true; break; 2924 } 2925 Class<?> src = newType.parameterType(i); 2926 Class<?> dst = oldType.parameterType(j); 2927 if (src != dst) 2928 throw newIllegalArgumentException("parameter types do not match after reorder", 2929 oldType, newType); 2930 } 2931 if (!bad) return true; 2932 } 2933 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 2934 } 2935 2936 /** 2937 * Produces a method handle of the requested return type which returns the given 2938 * constant value every time it is invoked. 2939 * <p> 2940 * Before the method handle is returned, the passed-in value is converted to the requested type. 2941 * If the requested type is primitive, widening primitive conversions are attempted, 2942 * else reference conversions are attempted. 2943 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 2944 * @param type the return type of the desired method handle 2945 * @param value the value to return 2946 * @return a method handle of the given return type and no arguments, which always returns the given value 2947 * @throws NullPointerException if the {@code type} argument is null 2948 * @throws ClassCastException if the value cannot be converted to the required return type 2949 * @throws IllegalArgumentException if the given type is {@code void.class} 2950 */ 2951 public static 2952 MethodHandle constant(Class<?> type, Object value) { 2953 if (type.isPrimitive()) { 2954 if (type == void.class) 2955 throw newIllegalArgumentException("void type"); 2956 Wrapper w = Wrapper.forPrimitiveType(type); 2957 value = w.convert(value, type); 2958 if (w.zero().equals(value)) 2959 return zero(w, type); 2960 return insertArguments(identity(type), 0, value); 2961 } else { 2962 if (value == null) 2963 return zero(Wrapper.OBJECT, type); 2964 return identity(type).bindTo(value); 2965 } 2966 } 2967 2968 /** 2969 * Produces a method handle which returns its sole argument when invoked. 2970 * @param type the type of the sole parameter and return value of the desired method handle 2971 * @return a unary method handle which accepts and returns the given type 2972 * @throws NullPointerException if the argument is null 2973 * @throws IllegalArgumentException if the given type is {@code void.class} 2974 */ 2975 public static 2976 MethodHandle identity(Class<?> type) { 2977 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 2978 int pos = btw.ordinal(); 2979 MethodHandle ident = IDENTITY_MHS[pos]; 2980 if (ident == null) { 2981 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 2982 } 2983 if (ident.type().returnType() == type) 2984 return ident; 2985 // something like identity(Foo.class); do not bother to intern these 2986 assert (btw == Wrapper.OBJECT); 2987 return makeIdentity(type); 2988 } 2989 2990 /** 2991 * Produces a constant method handle of the requested return type which 2992 * returns the default value for that type every time it is invoked. 2993 * The resulting constant method handle will have no side effects. 2994 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 2995 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 2996 * since {@code explicitCastArguments} converts {@code null} to default values. 2997 * @param type the expected return type of the desired method handle 2998 * @return a constant method handle that takes no arguments 2999 * and returns the default value of the given type (or void, if the type is void) 3000 * @throws NullPointerException if the argument is null 3001 * @see MethodHandles#constant 3002 * @see MethodHandles#empty 3003 * @since 9 3004 */ 3005 public static MethodHandle zero(Class<?> type) { 3006 Objects.requireNonNull(type); 3007 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 3008 } 3009 3010 private static MethodHandle identityOrVoid(Class<?> type) { 3011 return type == void.class ? zero(type) : identity(type); 3012 } 3013 3014 /** 3015 * Produces a method handle of the requested type which ignores any arguments, does nothing, 3016 * and returns a suitable default depending on the return type. 3017 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 3018 * <p>The returned method handle is equivalent to 3019 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 3020 * <p> 3021 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 3022 * {@code guardWithTest(pred, target, empty(target.type())}. 3023 * @param type the type of the desired method handle 3024 * @return a constant method handle of the given type, which returns a default value of the given return type 3025 * @throws NullPointerException if the argument is null 3026 * @see MethodHandles#zero 3027 * @see MethodHandles#constant 3028 * @since 9 3029 */ 3030 public static MethodHandle empty(MethodType type) { 3031 Objects.requireNonNull(type); 3032 return dropArguments(zero(type.returnType()), 0, type.parameterList()); 3033 } 3034 3035 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length]; 3036 private static MethodHandle makeIdentity(Class<?> ptype) { 3037 MethodType mtype = methodType(ptype, ptype); 3038 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 3039 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 3040 } 3041 3042 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 3043 int pos = btw.ordinal(); 3044 MethodHandle zero = ZERO_MHS[pos]; 3045 if (zero == null) { 3046 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 3047 } 3048 if (zero.type().returnType() == rtype) 3049 return zero; 3050 assert(btw == Wrapper.OBJECT); 3051 return makeZero(rtype); 3052 } 3053 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length]; 3054 private static MethodHandle makeZero(Class<?> rtype) { 3055 MethodType mtype = methodType(rtype); 3056 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 3057 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 3058 } 3059 3060 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 3061 // Simulate a CAS, to avoid racy duplication of results. 3062 MethodHandle prev = cache[pos]; 3063 if (prev != null) return prev; 3064 return cache[pos] = value; 3065 } 3066 3067 /** 3068 * Provides a target method handle with one or more <em>bound arguments</em> 3069 * in advance of the method handle's invocation. 3070 * The formal parameters to the target corresponding to the bound 3071 * arguments are called <em>bound parameters</em>. 3072 * Returns a new method handle which saves away the bound arguments. 3073 * When it is invoked, it receives arguments for any non-bound parameters, 3074 * binds the saved arguments to their corresponding parameters, 3075 * and calls the original target. 3076 * <p> 3077 * The type of the new method handle will drop the types for the bound 3078 * parameters from the original target type, since the new method handle 3079 * will no longer require those arguments to be supplied by its callers. 3080 * <p> 3081 * Each given argument object must match the corresponding bound parameter type. 3082 * If a bound parameter type is a primitive, the argument object 3083 * must be a wrapper, and will be unboxed to produce the primitive value. 3084 * <p> 3085 * The {@code pos} argument selects which parameters are to be bound. 3086 * It may range between zero and <i>N-L</i> (inclusively), 3087 * where <i>N</i> is the arity of the target method handle 3088 * and <i>L</i> is the length of the values array. 3089 * <p> 3090 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3091 * variable-arity method handle}, even if the original target method handle was. 3092 * @param target the method handle to invoke after the argument is inserted 3093 * @param pos where to insert the argument (zero for the first) 3094 * @param values the series of arguments to insert 3095 * @return a method handle which inserts an additional argument, 3096 * before calling the original method handle 3097 * @throws NullPointerException if the target or the {@code values} array is null 3098 * @see MethodHandle#bindTo 3099 */ 3100 public static 3101 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 3102 int insCount = values.length; 3103 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 3104 if (insCount == 0) return target; 3105 BoundMethodHandle result = target.rebind(); 3106 for (int i = 0; i < insCount; i++) { 3107 Object value = values[i]; 3108 Class<?> ptype = ptypes[pos+i]; 3109 if (ptype.isPrimitive()) { 3110 result = insertArgumentPrimitive(result, pos, ptype, value); 3111 } else { 3112 value = ptype.cast(value); // throw CCE if needed 3113 result = result.bindArgumentL(pos, value); 3114 } 3115 } 3116 return result; 3117 } 3118 3119 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 3120 Class<?> ptype, Object value) { 3121 Wrapper w = Wrapper.forPrimitiveType(ptype); 3122 // perform unboxing and/or primitive conversion 3123 value = w.convert(value, ptype); 3124 switch (w) { 3125 case INT: return result.bindArgumentI(pos, (int)value); 3126 case LONG: return result.bindArgumentJ(pos, (long)value); 3127 case FLOAT: return result.bindArgumentF(pos, (float)value); 3128 case DOUBLE: return result.bindArgumentD(pos, (double)value); 3129 default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 3130 } 3131 } 3132 3133 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 3134 MethodType oldType = target.type(); 3135 int outargs = oldType.parameterCount(); 3136 int inargs = outargs - insCount; 3137 if (inargs < 0) 3138 throw newIllegalArgumentException("too many values to insert"); 3139 if (pos < 0 || pos > inargs) 3140 throw newIllegalArgumentException("no argument type to append"); 3141 return oldType.ptypes(); 3142 } 3143 3144 /** 3145 * Produces a method handle which will discard some dummy arguments 3146 * before calling some other specified <i>target</i> method handle. 3147 * The type of the new method handle will be the same as the target's type, 3148 * except it will also include the dummy argument types, 3149 * at some given position. 3150 * <p> 3151 * The {@code pos} argument may range between zero and <i>N</i>, 3152 * where <i>N</i> is the arity of the target. 3153 * If {@code pos} is zero, the dummy arguments will precede 3154 * the target's real arguments; if {@code pos} is <i>N</i> 3155 * they will come after. 3156 * <p> 3157 * <b>Example:</b> 3158 * <blockquote><pre>{@code 3159 import static java.lang.invoke.MethodHandles.*; 3160 import static java.lang.invoke.MethodType.*; 3161 ... 3162 MethodHandle cat = lookup().findVirtual(String.class, 3163 "concat", methodType(String.class, String.class)); 3164 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3165 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 3166 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 3167 assertEquals(bigType, d0.type()); 3168 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 3169 * }</pre></blockquote> 3170 * <p> 3171 * This method is also equivalent to the following code: 3172 * <blockquote><pre> 3173 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 3174 * </pre></blockquote> 3175 * @param target the method handle to invoke after the arguments are dropped 3176 * @param valueTypes the type(s) of the argument(s) to drop 3177 * @param pos position of first argument to drop (zero for the leftmost) 3178 * @return a method handle which drops arguments of the given types, 3179 * before calling the original method handle 3180 * @throws NullPointerException if the target is null, 3181 * or if the {@code valueTypes} list or any of its elements is null 3182 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3183 * or if {@code pos} is negative or greater than the arity of the target, 3184 * or if the new method handle's type would have too many parameters 3185 */ 3186 public static 3187 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3188 MethodType oldType = target.type(); // get NPE 3189 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 3190 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 3191 if (dropped == 0) return target; 3192 BoundMethodHandle result = target.rebind(); 3193 LambdaForm lform = result.form; 3194 int insertFormArg = 1 + pos; 3195 for (Class<?> ptype : valueTypes) { 3196 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 3197 } 3198 result = result.copyWith(newType, lform); 3199 return result; 3200 } 3201 3202 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { 3203 int dropped = valueTypes.size(); 3204 MethodType.checkSlotCount(dropped); 3205 int outargs = oldType.parameterCount(); 3206 int inargs = outargs + dropped; 3207 if (pos < 0 || pos > outargs) 3208 throw newIllegalArgumentException("no argument type to remove" 3209 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 3210 ); 3211 return dropped; 3212 } 3213 3214 /** 3215 * Produces a method handle which will discard some dummy arguments 3216 * before calling some other specified <i>target</i> method handle. 3217 * The type of the new method handle will be the same as the target's type, 3218 * except it will also include the dummy argument types, 3219 * at some given position. 3220 * <p> 3221 * The {@code pos} argument may range between zero and <i>N</i>, 3222 * where <i>N</i> is the arity of the target. 3223 * If {@code pos} is zero, the dummy arguments will precede 3224 * the target's real arguments; if {@code pos} is <i>N</i> 3225 * they will come after. 3226 * @apiNote 3227 * <blockquote><pre>{@code 3228 import static java.lang.invoke.MethodHandles.*; 3229 import static java.lang.invoke.MethodType.*; 3230 ... 3231 MethodHandle cat = lookup().findVirtual(String.class, 3232 "concat", methodType(String.class, String.class)); 3233 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3234 MethodHandle d0 = dropArguments(cat, 0, String.class); 3235 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 3236 MethodHandle d1 = dropArguments(cat, 1, String.class); 3237 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 3238 MethodHandle d2 = dropArguments(cat, 2, String.class); 3239 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 3240 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 3241 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 3242 * }</pre></blockquote> 3243 * <p> 3244 * This method is also equivalent to the following code: 3245 * <blockquote><pre> 3246 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 3247 * </pre></blockquote> 3248 * @param target the method handle to invoke after the arguments are dropped 3249 * @param valueTypes the type(s) of the argument(s) to drop 3250 * @param pos position of first argument to drop (zero for the leftmost) 3251 * @return a method handle which drops arguments of the given types, 3252 * before calling the original method handle 3253 * @throws NullPointerException if the target is null, 3254 * or if the {@code valueTypes} array or any of its elements is null 3255 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3256 * or if {@code pos} is negative or greater than the arity of the target, 3257 * or if the new method handle's type would have 3258 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3259 */ 3260 public static 3261 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 3262 return dropArguments(target, pos, Arrays.asList(valueTypes)); 3263 } 3264 3265 // private version which allows caller some freedom with error handling 3266 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, 3267 boolean nullOnFailure) { 3268 List<Class<?>> oldTypes = target.type().parameterList(); 3269 int match = oldTypes.size(); 3270 if (skip != 0) { 3271 if (skip < 0 || skip > match) { 3272 throw newIllegalArgumentException("illegal skip", skip, target); 3273 } 3274 oldTypes = oldTypes.subList(skip, match); 3275 match -= skip; 3276 } 3277 List<Class<?>> addTypes = newTypes; 3278 int add = addTypes.size(); 3279 if (pos != 0) { 3280 if (pos < 0 || pos > add) { 3281 throw newIllegalArgumentException("illegal pos", pos, newTypes); 3282 } 3283 addTypes = addTypes.subList(pos, add); 3284 add -= pos; assert(addTypes.size() == add); 3285 } 3286 // Do not add types which already match the existing arguments. 3287 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { 3288 if (nullOnFailure) { 3289 return null; 3290 } 3291 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); 3292 } 3293 addTypes = addTypes.subList(match, add); 3294 add -= match; assert(addTypes.size() == add); 3295 // newTypes: ( P*[pos], M*[match], A*[add] ) 3296 // target: ( S*[skip], M*[match] ) 3297 MethodHandle adapter = target; 3298 if (add > 0) { 3299 adapter = dropArguments(adapter, skip+ match, addTypes); 3300 } 3301 // adapter: (S*[skip], M*[match], A*[add] ) 3302 if (pos > 0) { 3303 adapter = dropArguments(adapter, skip, newTypes.subList(0, pos)); 3304 } 3305 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 3306 return adapter; 3307 } 3308 3309 /** 3310 * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments. 3311 * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored. 3312 * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list, 3313 * at the given position. 3314 * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding 3315 * positions of the target method handle's parameters, as if by {@link #dropArguments}. 3316 * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip}, 3317 * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the 3318 * target list.) 3319 * The target's return type will be unchanged. 3320 * @apiNote 3321 * Two method handles whose argument lists are "effectively identical" (i.e., identical 3322 * in a common prefix) may be mutually converted to a common type 3323 * by two calls to {@code dropArgumentsToMatch}, as follows: 3324 * <blockquote><pre>{@code 3325 import static java.lang.invoke.MethodHandles.*; 3326 import static java.lang.invoke.MethodType.*; 3327 ... 3328 ... 3329 MethodHandle h0 = constant(boolean.class, true); 3330 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 3331 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 3332 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 3333 if (h1.type().parameterCount() < h2.type().parameterCount()) 3334 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 3335 else 3336 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 3337 MethodHandle h3 = guardWithTest(h0, h1, h2); 3338 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 3339 * }</pre></blockquote> 3340 * @param target the method handle to adapt 3341 * @param skip number of targets parameters to disregard (they will be unchanged) 3342 * @param newTypes the desired argument list of the method handle 3343 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 3344 * @return a possibly adapted method handle 3345 * @throws NullPointerException if either argument is null 3346 * @throws IllegalArgumentException 3347 * if either index is out of range in its corresponding list, or 3348 * if the non-skipped target parameter types match the new types at {@code pos} 3349 * @since 9 3350 */ 3351 public static 3352 MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 3353 Objects.requireNonNull(target); 3354 Objects.requireNonNull(newTypes); 3355 return dropArgumentsToMatch(target, skip, newTypes, pos, false); 3356 } 3357 3358 /** 3359 * Adapts a target method handle by pre-processing 3360 * one or more of its arguments, each with its own unary filter function, 3361 * and then calling the target with each pre-processed argument 3362 * replaced by the result of its corresponding filter function. 3363 * <p> 3364 * The pre-processing is performed by one or more method handles, 3365 * specified in the elements of the {@code filters} array. 3366 * The first element of the filter array corresponds to the {@code pos} 3367 * argument of the target, and so on in sequence. 3368 * <p> 3369 * Null arguments in the array are treated as identity functions, 3370 * and the corresponding arguments left unchanged. 3371 * (If there are no non-null elements in the array, the original target is returned.) 3372 * Each filter is applied to the corresponding argument of the adapter. 3373 * <p> 3374 * If a filter {@code F} applies to the {@code N}th argument of 3375 * the target, then {@code F} must be a method handle which 3376 * takes exactly one argument. The type of {@code F}'s sole argument 3377 * replaces the corresponding argument type of the target 3378 * in the resulting adapted method handle. 3379 * The return type of {@code F} must be identical to the corresponding 3380 * parameter type of the target. 3381 * <p> 3382 * It is an error if there are elements of {@code filters} 3383 * (null or not) 3384 * which do not correspond to argument positions in the target. 3385 * <p><b>Example:</b> 3386 * <blockquote><pre>{@code 3387 import static java.lang.invoke.MethodHandles.*; 3388 import static java.lang.invoke.MethodType.*; 3389 ... 3390 MethodHandle cat = lookup().findVirtual(String.class, 3391 "concat", methodType(String.class, String.class)); 3392 MethodHandle upcase = lookup().findVirtual(String.class, 3393 "toUpperCase", methodType(String.class)); 3394 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3395 MethodHandle f0 = filterArguments(cat, 0, upcase); 3396 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 3397 MethodHandle f1 = filterArguments(cat, 1, upcase); 3398 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 3399 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 3400 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 3401 * }</pre></blockquote> 3402 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3403 * denotes the return type of both the {@code target} and resulting adapter. 3404 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 3405 * of the parameters and arguments that precede and follow the filter position 3406 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 3407 * values of the filtered parameters and arguments; they also represent the 3408 * return types of the {@code filter[i]} handles. The latter accept arguments 3409 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 3410 * the resulting adapter. 3411 * <blockquote><pre>{@code 3412 * T target(P... p, A[i]... a[i], B... b); 3413 * A[i] filter[i](V[i]); 3414 * T adapter(P... p, V[i]... v[i], B... b) { 3415 * return target(p..., filter[i](v[i])..., b...); 3416 * } 3417 * }</pre></blockquote> 3418 * <p> 3419 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3420 * variable-arity method handle}, even if the original target method handle was. 3421 * 3422 * @param target the method handle to invoke after arguments are filtered 3423 * @param pos the position of the first argument to filter 3424 * @param filters method handles to call initially on filtered arguments 3425 * @return method handle which incorporates the specified argument filtering logic 3426 * @throws NullPointerException if the target is null 3427 * or if the {@code filters} array is null 3428 * @throws IllegalArgumentException if a non-null element of {@code filters} 3429 * does not match a corresponding argument type of target as described above, 3430 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 3431 * or if the resulting method handle's type would have 3432 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3433 */ 3434 public static 3435 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 3436 filterArgumentsCheckArity(target, pos, filters); 3437 MethodHandle adapter = target; 3438 int curPos = pos-1; // pre-incremented 3439 for (MethodHandle filter : filters) { 3440 curPos += 1; 3441 if (filter == null) continue; // ignore null elements of filters 3442 adapter = filterArgument(adapter, curPos, filter); 3443 } 3444 return adapter; 3445 } 3446 3447 /*non-public*/ static 3448 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 3449 filterArgumentChecks(target, pos, filter); 3450 MethodType targetType = target.type(); 3451 MethodType filterType = filter.type(); 3452 BoundMethodHandle result = target.rebind(); 3453 Class<?> newParamType = filterType.parameterType(0); 3454 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 3455 MethodType newType = targetType.changeParameterType(pos, newParamType); 3456 result = result.copyWithExtendL(newType, lform, filter); 3457 return result; 3458 } 3459 3460 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 3461 MethodType targetType = target.type(); 3462 int maxPos = targetType.parameterCount(); 3463 if (pos + filters.length > maxPos) 3464 throw newIllegalArgumentException("too many filters"); 3465 } 3466 3467 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3468 MethodType targetType = target.type(); 3469 MethodType filterType = filter.type(); 3470 if (filterType.parameterCount() != 1 3471 || filterType.returnType() != targetType.parameterType(pos)) 3472 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3473 } 3474 3475 /** 3476 * Adapts a target method handle by pre-processing 3477 * a sub-sequence of its arguments with a filter (another method handle). 3478 * The pre-processed arguments are replaced by the result (if any) of the 3479 * filter function. 3480 * The target is then called on the modified (usually shortened) argument list. 3481 * <p> 3482 * If the filter returns a value, the target must accept that value as 3483 * its argument in position {@code pos}, preceded and/or followed by 3484 * any arguments not passed to the filter. 3485 * If the filter returns void, the target must accept all arguments 3486 * not passed to the filter. 3487 * No arguments are reordered, and a result returned from the filter 3488 * replaces (in order) the whole subsequence of arguments originally 3489 * passed to the adapter. 3490 * <p> 3491 * The argument types (if any) of the filter 3492 * replace zero or one argument types of the target, at position {@code pos}, 3493 * in the resulting adapted method handle. 3494 * The return type of the filter (if any) must be identical to the 3495 * argument type of the target at position {@code pos}, and that target argument 3496 * is supplied by the return value of the filter. 3497 * <p> 3498 * In all cases, {@code pos} must be greater than or equal to zero, and 3499 * {@code pos} must also be less than or equal to the target's arity. 3500 * <p><b>Example:</b> 3501 * <blockquote><pre>{@code 3502 import static java.lang.invoke.MethodHandles.*; 3503 import static java.lang.invoke.MethodType.*; 3504 ... 3505 MethodHandle deepToString = publicLookup() 3506 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 3507 3508 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 3509 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 3510 3511 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 3512 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 3513 3514 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 3515 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 3516 assertEquals("[top, [up, down], strange]", 3517 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 3518 3519 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 3520 assertEquals("[top, [up, down], [strange]]", 3521 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 3522 3523 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 3524 assertEquals("[top, [[up, down, strange], charm], bottom]", 3525 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 3526 * }</pre></blockquote> 3527 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3528 * represents the return type of the {@code target} and resulting adapter. 3529 * {@code V}/{@code v} stand for the return type and value of the 3530 * {@code filter}, which are also found in the signature and arguments of 3531 * the {@code target}, respectively, unless {@code V} is {@code void}. 3532 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 3533 * and values preceding and following the collection position, {@code pos}, 3534 * in the {@code target}'s signature. They also turn up in the resulting 3535 * adapter's signature and arguments, where they surround 3536 * {@code B}/{@code b}, which represent the parameter types and arguments 3537 * to the {@code filter} (if any). 3538 * <blockquote><pre>{@code 3539 * T target(A...,V,C...); 3540 * V filter(B...); 3541 * T adapter(A... a,B... b,C... c) { 3542 * V v = filter(b...); 3543 * return target(a...,v,c...); 3544 * } 3545 * // and if the filter has no arguments: 3546 * T target2(A...,V,C...); 3547 * V filter2(); 3548 * T adapter2(A... a,C... c) { 3549 * V v = filter2(); 3550 * return target2(a...,v,c...); 3551 * } 3552 * // and if the filter has a void return: 3553 * T target3(A...,C...); 3554 * void filter3(B...); 3555 * T adapter3(A... a,B... b,C... c) { 3556 * filter3(b...); 3557 * return target3(a...,c...); 3558 * } 3559 * }</pre></blockquote> 3560 * <p> 3561 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 3562 * one which first "folds" the affected arguments, and then drops them, in separate 3563 * steps as follows: 3564 * <blockquote><pre>{@code 3565 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 3566 * mh = MethodHandles.foldArguments(mh, coll); //step 1 3567 * }</pre></blockquote> 3568 * If the target method handle consumes no arguments besides than the result 3569 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 3570 * is equivalent to {@code filterReturnValue(coll, mh)}. 3571 * If the filter method handle {@code coll} consumes one argument and produces 3572 * a non-void result, then {@code collectArguments(mh, N, coll)} 3573 * is equivalent to {@code filterArguments(mh, N, coll)}. 3574 * Other equivalences are possible but would require argument permutation. 3575 * <p> 3576 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3577 * variable-arity method handle}, even if the original target method handle was. 3578 * 3579 * @param target the method handle to invoke after filtering the subsequence of arguments 3580 * @param pos the position of the first adapter argument to pass to the filter, 3581 * and/or the target argument which receives the result of the filter 3582 * @param filter method handle to call on the subsequence of arguments 3583 * @return method handle which incorporates the specified argument subsequence filtering logic 3584 * @throws NullPointerException if either argument is null 3585 * @throws IllegalArgumentException if the return type of {@code filter} 3586 * is non-void and is not the same as the {@code pos} argument of the target, 3587 * or if {@code pos} is not between 0 and the target's arity, inclusive, 3588 * or if the resulting method handle's type would have 3589 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3590 * @see MethodHandles#foldArguments 3591 * @see MethodHandles#filterArguments 3592 * @see MethodHandles#filterReturnValue 3593 */ 3594 public static 3595 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 3596 MethodType newType = collectArgumentsChecks(target, pos, filter); 3597 MethodType collectorType = filter.type(); 3598 BoundMethodHandle result = target.rebind(); 3599 LambdaForm lform; 3600 if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { 3601 lform = result.editor().collectArgumentArrayForm(1 + pos, filter); 3602 if (lform != null) { 3603 return result.copyWith(newType, lform); 3604 } 3605 } 3606 lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 3607 return result.copyWithExtendL(newType, lform, filter); 3608 } 3609 3610 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3611 MethodType targetType = target.type(); 3612 MethodType filterType = filter.type(); 3613 Class<?> rtype = filterType.returnType(); 3614 List<Class<?>> filterArgs = filterType.parameterList(); 3615 if (rtype == void.class) { 3616 return targetType.insertParameterTypes(pos, filterArgs); 3617 } 3618 if (rtype != targetType.parameterType(pos)) { 3619 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3620 } 3621 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); 3622 } 3623 3624 /** 3625 * Adapts a target method handle by post-processing 3626 * its return value (if any) with a filter (another method handle). 3627 * The result of the filter is returned from the adapter. 3628 * <p> 3629 * If the target returns a value, the filter must accept that value as 3630 * its only argument. 3631 * If the target returns void, the filter must accept no arguments. 3632 * <p> 3633 * The return type of the filter 3634 * replaces the return type of the target 3635 * in the resulting adapted method handle. 3636 * The argument type of the filter (if any) must be identical to the 3637 * return type of the target. 3638 * <p><b>Example:</b> 3639 * <blockquote><pre>{@code 3640 import static java.lang.invoke.MethodHandles.*; 3641 import static java.lang.invoke.MethodType.*; 3642 ... 3643 MethodHandle cat = lookup().findVirtual(String.class, 3644 "concat", methodType(String.class, String.class)); 3645 MethodHandle length = lookup().findVirtual(String.class, 3646 "length", methodType(int.class)); 3647 System.out.println((String) cat.invokeExact("x", "y")); // xy 3648 MethodHandle f0 = filterReturnValue(cat, length); 3649 System.out.println((int) f0.invokeExact("x", "y")); // 2 3650 * }</pre></blockquote> 3651 * <p>Here is pseudocode for the resulting adapter. In the code, 3652 * {@code T}/{@code t} represent the result type and value of the 3653 * {@code target}; {@code V}, the result type of the {@code filter}; and 3654 * {@code A}/{@code a}, the types and values of the parameters and arguments 3655 * of the {@code target} as well as the resulting adapter. 3656 * <blockquote><pre>{@code 3657 * T target(A...); 3658 * V filter(T); 3659 * V adapter(A... a) { 3660 * T t = target(a...); 3661 * return filter(t); 3662 * } 3663 * // and if the target has a void return: 3664 * void target2(A...); 3665 * V filter2(); 3666 * V adapter2(A... a) { 3667 * target2(a...); 3668 * return filter2(); 3669 * } 3670 * // and if the filter has a void return: 3671 * T target3(A...); 3672 * void filter3(V); 3673 * void adapter3(A... a) { 3674 * T t = target3(a...); 3675 * filter3(t); 3676 * } 3677 * }</pre></blockquote> 3678 * <p> 3679 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3680 * variable-arity method handle}, even if the original target method handle was. 3681 * @param target the method handle to invoke before filtering the return value 3682 * @param filter method handle to call on the return value 3683 * @return method handle which incorporates the specified return value filtering logic 3684 * @throws NullPointerException if either argument is null 3685 * @throws IllegalArgumentException if the argument list of {@code filter} 3686 * does not match the return type of target as described above 3687 */ 3688 public static 3689 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 3690 MethodType targetType = target.type(); 3691 MethodType filterType = filter.type(); 3692 filterReturnValueChecks(targetType, filterType); 3693 BoundMethodHandle result = target.rebind(); 3694 BasicType rtype = BasicType.basicType(filterType.returnType()); 3695 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 3696 MethodType newType = targetType.changeReturnType(filterType.returnType()); 3697 result = result.copyWithExtendL(newType, lform, filter); 3698 return result; 3699 } 3700 3701 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 3702 Class<?> rtype = targetType.returnType(); 3703 int filterValues = filterType.parameterCount(); 3704 if (filterValues == 0 3705 ? (rtype != void.class) 3706 : (rtype != filterType.parameterType(0))) 3707 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3708 } 3709 3710 /** 3711 * Adapts a target method handle by pre-processing 3712 * some of its arguments, and then calling the target with 3713 * the result of the pre-processing, inserted into the original 3714 * sequence of arguments. 3715 * <p> 3716 * The pre-processing is performed by {@code combiner}, a second method handle. 3717 * Of the arguments passed to the adapter, the first {@code N} arguments 3718 * are copied to the combiner, which is then called. 3719 * (Here, {@code N} is defined as the parameter count of the combiner.) 3720 * After this, control passes to the target, with any result 3721 * from the combiner inserted before the original {@code N} incoming 3722 * arguments. 3723 * <p> 3724 * If the combiner returns a value, the first parameter type of the target 3725 * must be identical with the return type of the combiner, and the next 3726 * {@code N} parameter types of the target must exactly match the parameters 3727 * of the combiner. 3728 * <p> 3729 * If the combiner has a void return, no result will be inserted, 3730 * and the first {@code N} parameter types of the target 3731 * must exactly match the parameters of the combiner. 3732 * <p> 3733 * The resulting adapter is the same type as the target, except that the 3734 * first parameter type is dropped, 3735 * if it corresponds to the result of the combiner. 3736 * <p> 3737 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 3738 * that either the combiner or the target does not wish to receive. 3739 * If some of the incoming arguments are destined only for the combiner, 3740 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 3741 * arguments will not need to be live on the stack on entry to the 3742 * target.) 3743 * <p><b>Example:</b> 3744 * <blockquote><pre>{@code 3745 import static java.lang.invoke.MethodHandles.*; 3746 import static java.lang.invoke.MethodType.*; 3747 ... 3748 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 3749 "println", methodType(void.class, String.class)) 3750 .bindTo(System.out); 3751 MethodHandle cat = lookup().findVirtual(String.class, 3752 "concat", methodType(String.class, String.class)); 3753 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 3754 MethodHandle catTrace = foldArguments(cat, trace); 3755 // also prints "boo": 3756 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 3757 * }</pre></blockquote> 3758 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3759 * represents the result type of the {@code target} and resulting adapter. 3760 * {@code V}/{@code v} represent the type and value of the parameter and argument 3761 * of {@code target} that precedes the folding position; {@code V} also is 3762 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 3763 * types and values of the {@code N} parameters and arguments at the folding 3764 * position. {@code B}/{@code b} represent the types and values of the 3765 * {@code target} parameters and arguments that follow the folded parameters 3766 * and arguments. 3767 * <blockquote><pre>{@code 3768 * // there are N arguments in A... 3769 * T target(V, A[N]..., B...); 3770 * V combiner(A...); 3771 * T adapter(A... a, B... b) { 3772 * V v = combiner(a...); 3773 * return target(v, a..., b...); 3774 * } 3775 * // and if the combiner has a void return: 3776 * T target2(A[N]..., B...); 3777 * void combiner2(A...); 3778 * T adapter2(A... a, B... b) { 3779 * combiner2(a...); 3780 * return target2(a..., b...); 3781 * } 3782 * }</pre></blockquote> 3783 * <p> 3784 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3785 * variable-arity method handle}, even if the original target method handle was. 3786 * @param target the method handle to invoke after arguments are combined 3787 * @param combiner method handle to call initially on the incoming arguments 3788 * @return method handle which incorporates the specified argument folding logic 3789 * @throws NullPointerException if either argument is null 3790 * @throws IllegalArgumentException if {@code combiner}'s return type 3791 * is non-void and not the same as the first argument type of 3792 * the target, or if the initial {@code N} argument types 3793 * of the target 3794 * (skipping one matching the {@code combiner}'s return type) 3795 * are not identical with the argument types of {@code combiner} 3796 */ 3797 public static 3798 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 3799 return foldArguments(target, 0, combiner); 3800 } 3801 3802 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 3803 int foldArgs = combinerType.parameterCount(); 3804 Class<?> rtype = combinerType.returnType(); 3805 int foldVals = rtype == void.class ? 0 : 1; 3806 int afterInsertPos = foldPos + foldVals; 3807 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 3808 if (ok && !(combinerType.parameterList() 3809 .equals(targetType.parameterList().subList(afterInsertPos, 3810 afterInsertPos + foldArgs)))) 3811 ok = false; 3812 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 3813 ok = false; 3814 if (!ok) 3815 throw misMatchedTypes("target and combiner types", targetType, combinerType); 3816 return rtype; 3817 } 3818 3819 /** 3820 * Makes a method handle which adapts a target method handle, 3821 * by guarding it with a test, a boolean-valued method handle. 3822 * If the guard fails, a fallback handle is called instead. 3823 * All three method handles must have the same corresponding 3824 * argument and return types, except that the return type 3825 * of the test must be boolean, and the test is allowed 3826 * to have fewer arguments than the other two method handles. 3827 * <p> 3828 * Here is pseudocode for the resulting adapter. In the code, {@code T} 3829 * represents the uniform result type of the three involved handles; 3830 * {@code A}/{@code a}, the types and values of the {@code target} 3831 * parameters and arguments that are consumed by the {@code test}; and 3832 * {@code B}/{@code b}, those types and values of the {@code target} 3833 * parameters and arguments that are not consumed by the {@code test}. 3834 * <blockquote><pre>{@code 3835 * boolean test(A...); 3836 * T target(A...,B...); 3837 * T fallback(A...,B...); 3838 * T adapter(A... a,B... b) { 3839 * if (test(a...)) 3840 * return target(a..., b...); 3841 * else 3842 * return fallback(a..., b...); 3843 * } 3844 * }</pre></blockquote> 3845 * Note that the test arguments ({@code a...} in the pseudocode) cannot 3846 * be modified by execution of the test, and so are passed unchanged 3847 * from the caller to the target or fallback as appropriate. 3848 * @param test method handle used for test, must return boolean 3849 * @param target method handle to call if test passes 3850 * @param fallback method handle to call if test fails 3851 * @return method handle which incorporates the specified if/then/else logic 3852 * @throws NullPointerException if any argument is null 3853 * @throws IllegalArgumentException if {@code test} does not return boolean, 3854 * or if all three method types do not match (with the return 3855 * type of {@code test} changed to match that of the target). 3856 */ 3857 public static 3858 MethodHandle guardWithTest(MethodHandle test, 3859 MethodHandle target, 3860 MethodHandle fallback) { 3861 MethodType gtype = test.type(); 3862 MethodType ttype = target.type(); 3863 MethodType ftype = fallback.type(); 3864 if (!ttype.equals(ftype)) 3865 throw misMatchedTypes("target and fallback types", ttype, ftype); 3866 if (gtype.returnType() != boolean.class) 3867 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 3868 List<Class<?>> targs = ttype.parameterList(); 3869 test = dropArgumentsToMatch(test, 0, targs, 0, true); 3870 if (test == null) { 3871 throw misMatchedTypes("target and test types", ttype, gtype); 3872 } 3873 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 3874 } 3875 3876 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 3877 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 3878 } 3879 3880 /** 3881 * Makes a method handle which adapts a target method handle, 3882 * by running it inside an exception handler. 3883 * If the target returns normally, the adapter returns that value. 3884 * If an exception matching the specified type is thrown, the fallback 3885 * handle is called instead on the exception, plus the original arguments. 3886 * <p> 3887 * The target and handler must have the same corresponding 3888 * argument and return types, except that handler may omit trailing arguments 3889 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 3890 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 3891 * <p> 3892 * Here is pseudocode for the resulting adapter. In the code, {@code T} 3893 * represents the return type of the {@code target} and {@code handler}, 3894 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 3895 * the types and values of arguments to the resulting handle consumed by 3896 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 3897 * resulting handle discarded by {@code handler}. 3898 * <blockquote><pre>{@code 3899 * T target(A..., B...); 3900 * T handler(ExType, A...); 3901 * T adapter(A... a, B... b) { 3902 * try { 3903 * return target(a..., b...); 3904 * } catch (ExType ex) { 3905 * return handler(ex, a...); 3906 * } 3907 * } 3908 * }</pre></blockquote> 3909 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 3910 * be modified by execution of the target, and so are passed unchanged 3911 * from the caller to the handler, if the handler is invoked. 3912 * <p> 3913 * The target and handler must return the same type, even if the handler 3914 * always throws. (This might happen, for instance, because the handler 3915 * is simulating a {@code finally} clause). 3916 * To create such a throwing handler, compose the handler creation logic 3917 * with {@link #throwException throwException}, 3918 * in order to create a method handle of the correct return type. 3919 * @param target method handle to call 3920 * @param exType the type of exception which the handler will catch 3921 * @param handler method handle to call if a matching exception is thrown 3922 * @return method handle which incorporates the specified try/catch logic 3923 * @throws NullPointerException if any argument is null 3924 * @throws IllegalArgumentException if {@code handler} does not accept 3925 * the given exception type, or if the method handle types do 3926 * not match in their return types and their 3927 * corresponding parameters 3928 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 3929 */ 3930 public static 3931 MethodHandle catchException(MethodHandle target, 3932 Class<? extends Throwable> exType, 3933 MethodHandle handler) { 3934 MethodType ttype = target.type(); 3935 MethodType htype = handler.type(); 3936 if (!Throwable.class.isAssignableFrom(exType)) 3937 throw new ClassCastException(exType.getName()); 3938 if (htype.parameterCount() < 1 || 3939 !htype.parameterType(0).isAssignableFrom(exType)) 3940 throw newIllegalArgumentException("handler does not accept exception type "+exType); 3941 if (htype.returnType() != ttype.returnType()) 3942 throw misMatchedTypes("target and handler return types", ttype, htype); 3943 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); 3944 if (handler == null) { 3945 throw misMatchedTypes("target and handler types", ttype, htype); 3946 } 3947 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 3948 } 3949 3950 /** 3951 * Produces a method handle which will throw exceptions of the given {@code exType}. 3952 * The method handle will accept a single argument of {@code exType}, 3953 * and immediately throw it as an exception. 3954 * The method type will nominally specify a return of {@code returnType}. 3955 * The return type may be anything convenient: It doesn't matter to the 3956 * method handle's behavior, since it will never return normally. 3957 * @param returnType the return type of the desired method handle 3958 * @param exType the parameter type of the desired method handle 3959 * @return method handle which can throw the given exceptions 3960 * @throws NullPointerException if either argument is null 3961 */ 3962 public static 3963 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 3964 if (!Throwable.class.isAssignableFrom(exType)) 3965 throw new ClassCastException(exType.getName()); 3966 return MethodHandleImpl.throwException(methodType(returnType, exType)); 3967 } 3968 3969 /** 3970 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 3971 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 3972 * delivers the loop's result, which is the return value of the resulting handle. 3973 * <p> 3974 * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop 3975 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 3976 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 3977 * terms of method handles, each clause will determine four actions:<ul> 3978 * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local. 3979 * <li>When a clause executes, an update step for the iteration variable. 3980 * <li>When a clause executes, a predicate execution to test for loop exit. 3981 * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 3982 * </ul> 3983 * <p> 3984 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 3985 * this case. See below for a detailed description. 3986 * <p> 3987 * Each clause function, with the exception of clause initializers, is able to observe the entire loop state, 3988 * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop 3989 * parameters. Most clause functions will not need all of this information, but they will be formally connected as 3990 * if by {@link #dropArguments}. 3991 * <p> 3992 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 3993 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 3994 * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met 3995 * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means 3996 * that they must be identical, or else one list must be a proper prefix of the other. 3997 * <p> 3998 * <em>Step 0: Determine clause structure.</em><ol type="a"> 3999 * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element. 4000 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 4001 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 4002 * four. Padding takes place by appending elements to the array. 4003 * <li>Clauses with all {@code null}s are disregarded. 4004 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 4005 * </ol> 4006 * <p> 4007 * <em>Step 1A: Determine iteration variables.</em><ol type="a"> 4008 * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type. 4009 * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else 4010 * use the common return type (they must be identical). 4011 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 4012 * <li>This list of types is called the "common prefix". 4013 * </ol> 4014 * <p> 4015 * <em>Step 1B: Determine loop parameters.</em><ul> 4016 * <li><b>If at least one init function is given,</b><ol type="a"> 4017 * <li>Examine init function parameter lists. 4018 * <li>Omitted init functions are deemed to have {@code null} parameter lists. 4019 * <li>All init function parameter lists must be effectively identical. 4020 * <li>The longest parameter list (which is necessarily unique) is called the "common suffix". 4021 * </ol> 4022 * <li><b>If no init function is given,</b><ol type="a"> 4023 * <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix". 4024 * <li>The longest of these suffixes is taken as the "common suffix". 4025 * </ol></ul> 4026 * <p> 4027 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 4028 * <li>Examine fini function return types, disregarding omitted fini functions. 4029 * <li>If there are no fini functions, use {@code void} as the loop return type. 4030 * <li>Otherwise, use the common return type of the fini functions; they must all be identical. 4031 * </ol> 4032 * <p> 4033 * <em>Step 1D: Check other types.</em><ol type="a"> 4034 * <li>There must be at least one non-omitted pred function. 4035 * <li>Every non-omitted pred function must have a {@code boolean} return type. 4036 * </ol> 4037 * <p> 4038 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 4039 * <li>The parameter list for the resulting loop handle will be the "common suffix". 4040 * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter 4041 * lists are already effectively identical to the common suffix.) 4042 * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix 4043 * followed by the common suffix, called the "common parameter sequence". 4044 * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter 4045 * sequence. 4046 * </ol> 4047 * <p> 4048 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 4049 * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate 4050 * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a 4051 * function which does nothing and returns {@code void}; it can be obtained from another constant function by 4052 * {@linkplain MethodHandle#asType type conversion}.) 4053 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 4054 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 4055 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 4056 * <li>If a pred function is omitted, the corresponding fini function must also be omitted. 4057 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 4058 * as this clause is concerned.) 4059 * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the 4060 * loop return type. 4061 * </ol> 4062 * <p> 4063 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 4064 * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some 4065 * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by 4066 * {@linkplain #dropArguments dropping arguments}. 4067 * <li>At this point, every non-init function parameter list is effectively identical to the common parameter 4068 * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end 4069 * of the list by {@linkplain #dropArguments dropping arguments}. 4070 * </ol> 4071 * <p> 4072 * <em>Final observations.</em><ol type="a"> 4073 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 4074 * <li>All init functions have a common parameter type list, which the final loop handle will also have. 4075 * <li>All fini functions have a common return type, which the final loop handle will also have. 4076 * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of 4077 * (non-{@code void}) iteration variables followed by loop parameters. 4078 * <li>Each pair of init and step functions agrees in their return types. 4079 * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the 4080 * common prefix. 4081 * </ol> 4082 * <p> 4083 * <em>Loop execution.</em><ol type="a"> 4084 * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to 4085 * every clause function. These locals are loop invariant. 4086 * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values 4087 * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity 4088 * functions, as noted above). 4089 * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of 4090 * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order). 4091 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 4092 * returns {@code false}. 4093 * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The 4094 * updated value is immediately visible to all subsequent function calls. 4095 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 4096 * is returned from the loop as a whole. 4097 * </ol> 4098 * <p> 4099 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values 4100 * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the 4101 * result types of finalizers as well as of the resulting loop. 4102 * <blockquote><pre>{@code 4103 * V... init...(A...); 4104 * boolean pred...(V..., A...); 4105 * V... step...(V..., A...); 4106 * R fini...(V..., A...); 4107 * R loop(A... a) { 4108 * V... v... = init...(a...); 4109 * for (;;) { 4110 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 4111 * v = s(v..., a...); 4112 * if (!p(v..., a...)) { 4113 * return f(v..., a...); 4114 * } 4115 * } 4116 * } 4117 * } 4118 * }</pre></blockquote> 4119 * <p> 4120 * @apiNote Example: 4121 * <blockquote><pre>{@code 4122 * // iterative implementation of the factorial function as a loop handle 4123 * static int one(int k) { return 1; } 4124 * static int inc(int i, int acc, int k) { return i + 1; } 4125 * static int mult(int i, int acc, int k) { return i * acc; } 4126 * static boolean pred(int i, int acc, int k) { return i < k; } 4127 * static int fin(int i, int acc, int k) { return acc; } 4128 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4129 * // null initializer for counter, should initialize to 0 4130 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4131 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4132 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4133 * assertEquals(120, loop.invoke(5)); 4134 * }</pre></blockquote> 4135 * 4136 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 4137 * 4138 * @return a method handle embodying the looping behavior as defined by the arguments. 4139 * 4140 * @throws IllegalArgumentException in case any of the constraints described above is violated. 4141 * 4142 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 4143 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 4144 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 4145 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 4146 * @since 9 4147 */ 4148 public static MethodHandle loop(MethodHandle[]... clauses) { 4149 // Step 0: determine clause structure. 4150 checkLoop0(clauses); 4151 4152 List<MethodHandle> init = new ArrayList<>(); 4153 List<MethodHandle> step = new ArrayList<>(); 4154 List<MethodHandle> pred = new ArrayList<>(); 4155 List<MethodHandle> fini = new ArrayList<>(); 4156 4157 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 4158 init.add(clause[0]); // all clauses have at least length 1 4159 step.add(clause.length <= 1 ? null : clause[1]); 4160 pred.add(clause.length <= 2 ? null : clause[2]); 4161 fini.add(clause.length <= 3 ? null : clause[3]); 4162 }); 4163 4164 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 4165 final int nclauses = init.size(); 4166 4167 // Step 1A: determine iteration variables. 4168 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 4169 for (int i = 0; i < nclauses; ++i) { 4170 MethodHandle in = init.get(i); 4171 MethodHandle st = step.get(i); 4172 if (in == null && st == null) { 4173 iterationVariableTypes.add(void.class); 4174 } else if (in != null && st != null) { 4175 checkLoop1a(i, in, st); 4176 iterationVariableTypes.add(in.type().returnType()); 4177 } else { 4178 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 4179 } 4180 } 4181 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). 4182 collect(Collectors.toList()); 4183 4184 // Step 1B: determine loop parameters. 4185 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 4186 checkLoop1b(init, commonSuffix); 4187 4188 // Step 1C: determine loop return type. 4189 // Step 1D: check other types. 4190 final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type). 4191 map(MethodType::returnType).findFirst().orElse(void.class); 4192 checkLoop1cd(pred, fini, loopReturnType); 4193 4194 // Step 2: determine parameter lists. 4195 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 4196 commonParameterSequence.addAll(commonSuffix); 4197 checkLoop2(step, pred, fini, commonParameterSequence); 4198 4199 // Step 3: fill in omitted functions. 4200 for (int i = 0; i < nclauses; ++i) { 4201 Class<?> t = iterationVariableTypes.get(i); 4202 if (init.get(i) == null) { 4203 init.set(i, empty(methodType(t, commonSuffix))); 4204 } 4205 if (step.get(i) == null) { 4206 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 4207 } 4208 if (pred.get(i) == null) { 4209 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 4210 } 4211 if (fini.get(i) == null) { 4212 fini.set(i, empty(methodType(t, commonParameterSequence))); 4213 } 4214 } 4215 4216 // Step 4: fill in missing parameter types. 4217 List<MethodHandle> finit = fillParameterTypes(init, commonSuffix); 4218 List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence); 4219 List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence); 4220 List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence); 4221 4222 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 4223 allMatch(pl -> pl.equals(commonSuffix)); 4224 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 4225 allMatch(pl -> pl.equals(commonParameterSequence)); 4226 4227 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, commonPrefix, finit, fstep, fpred, ffini); 4228 } 4229 4230 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 4231 return hs.stream().map(h -> { 4232 int pc = h.type().parameterCount(); 4233 int tpsize = targetParams.size(); 4234 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 4235 }).collect(Collectors.toList()); 4236 } 4237 4238 /** 4239 * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for 4240 * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 4241 * <p> 4242 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. 4243 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle 4244 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code 4245 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) 4246 * generic loop combinator}. 4247 * <p> 4248 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4249 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4250 * passed to the loop. 4251 * <blockquote><pre>{@code 4252 * V init(A); 4253 * boolean pred(V, A); 4254 * V body(V, A); 4255 * V whileLoop(A a) { 4256 * V v = init(a); 4257 * while (pred(v, a)) { 4258 * v = body(v, a); 4259 * } 4260 * return v; 4261 * } 4262 * }</pre></blockquote> 4263 * <p> 4264 * @apiNote Example: 4265 * <blockquote><pre>{@code 4266 * // implement the zip function for lists as a loop handle 4267 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 4268 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 4269 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 4270 * zip.add(a.next()); 4271 * zip.add(b.next()); 4272 * return zip; 4273 * } 4274 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 4275 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 4276 * List<String> a = Arrays.asList("a", "b", "c", "d"); 4277 * List<String> b = Arrays.asList("e", "f", "g", "h"); 4278 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 4279 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 4280 * }</pre></blockquote> 4281 * 4282 * <p> 4283 * @implSpec The implementation of this method is equivalent to: 4284 * <blockquote><pre>{@code 4285 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4286 * MethodHandle[] 4287 * checkExit = {null, null, pred, identity(init.type().returnType())}, 4288 * varBody = {init, body}; 4289 * return loop(checkExit, varBody); 4290 * } 4291 * }</pre></blockquote> 4292 * 4293 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's 4294 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type 4295 * {@code void}. 4296 * @param pred condition for the loop, which may not be {@code null}. 4297 * @param body body of the loop, which may not be {@code null}. 4298 * 4299 * @return the value of the loop variable as the loop terminates. 4300 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4301 * 4302 * @see MethodHandles#loop(MethodHandle[][]) 4303 * @since 9 4304 */ 4305 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4306 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : 4307 identity(init.type().returnType()); 4308 MethodHandle[] checkExit = {null, null, pred, fin}; 4309 MethodHandle[] varBody = {init, body}; 4310 return loop(checkExit, varBody); 4311 } 4312 4313 /** 4314 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper 4315 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4316 * <p> 4317 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. 4318 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle 4319 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code 4320 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) 4321 * generic loop combinator}. 4322 * <p> 4323 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4324 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4325 * passed to the loop. 4326 * <blockquote><pre>{@code 4327 * V init(A); 4328 * boolean pred(V, A); 4329 * V body(V, A); 4330 * V doWhileLoop(A a) { 4331 * V v = init(a); 4332 * do { 4333 * v = body(v, a); 4334 * } while (pred(v, a)); 4335 * return v; 4336 * } 4337 * }</pre></blockquote> 4338 * <p> 4339 * @apiNote Example: 4340 * <blockquote><pre>{@code 4341 * // int i = 0; while (i < limit) { ++i; } return i; => limit 4342 * static int zero(int limit) { return 0; } 4343 * static int step(int i, int limit) { return i + 1; } 4344 * static boolean pred(int i, int limit) { return i < limit; } 4345 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 4346 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 4347 * assertEquals(23, loop.invoke(23)); 4348 * }</pre></blockquote> 4349 * 4350 * <p> 4351 * @implSpec The implementation of this method is equivalent to: 4352 * <blockquote><pre>{@code 4353 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4354 * MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) }; 4355 * return loop(clause); 4356 * } 4357 * }</pre></blockquote> 4358 * 4359 * 4360 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's 4361 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type 4362 * {@code void}. 4363 * @param pred condition for the loop, which may not be {@code null}. 4364 * @param body body of the loop, which may not be {@code null}. 4365 * 4366 * @return the value of the loop variable as the loop terminates. 4367 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4368 * 4369 * @see MethodHandles#loop(MethodHandle[][]) 4370 * @since 9 4371 */ 4372 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4373 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : 4374 identity(init.type().returnType()); 4375 MethodHandle[] clause = {init, body, pred, fin}; 4376 return loop(clause); 4377 } 4378 4379 /** 4380 * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the 4381 * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must 4382 * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional 4383 * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop 4384 * combinator}. 4385 * <p> 4386 * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code 4387 * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code 4388 * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter, 4389 * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described 4390 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4391 * <p> 4392 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4393 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4394 * passed to the loop. 4395 * <blockquote><pre>{@code 4396 * int iterations(A); 4397 * V init(A); 4398 * V body(int, V, A); 4399 * V countedLoop(A a) { 4400 * int end = iterations(a); 4401 * V v = init(a); 4402 * for (int i = 0; i < end; ++i) { 4403 * v = body(i, v, a); 4404 * } 4405 * return v; 4406 * } 4407 * }</pre></blockquote> 4408 * <p> 4409 * @apiNote Example: 4410 * <blockquote><pre>{@code 4411 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 4412 * // => a variation on a well known theme 4413 * static String start(String arg) { return arg; } 4414 * static String step(int counter, String v, String arg) { return "na " + v; } 4415 * // assume MH_start and MH_step are handles to the two methods above 4416 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 4417 * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step); 4418 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 4419 * }</pre></blockquote> 4420 * 4421 * <p> 4422 * @implSpec The implementation of this method is equivalent to: 4423 * <blockquote><pre>{@code 4424 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4425 * return countedLoop(null, iterations, init, body); // null => constant zero 4426 * } 4427 * }</pre></blockquote> 4428 * 4429 * @param iterations a handle to return the number of iterations this loop should run. 4430 * @param init initializer for additional loop state. This determines the loop's result type. 4431 * Passing {@code null} or a {@code void} init function will make the loop's result type 4432 * {@code void}. 4433 * @param body the body of the loop, which must not be {@code null}. 4434 * It must accept an initial {@code int} parameter (for the counter), and then any 4435 * additional loop-local variable plus loop parameters. 4436 * 4437 * @return a method handle representing the loop. 4438 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4439 * 4440 * @since 9 4441 */ 4442 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4443 return countedLoop(null, iterations, init, body); 4444 } 4445 4446 /** 4447 * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be 4448 * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the 4449 * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code 4450 * body} function in each iteration; it has to accept an initial {@code int} parameter 4451 * for that. The result of the loop execution is the final value of the additional local state 4452 * obtained by running {@code init}. 4453 * This is a 4454 * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4455 * <p> 4456 * The constraints for the {@code init} and {@code body} handles are the same as for {@link 4457 * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles 4458 * must return an {@code int} and accept the same parameters as {@code init}. 4459 * <p> 4460 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4461 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4462 * passed to the loop. 4463 * <blockquote><pre>{@code 4464 * int start(A); 4465 * int end(A); 4466 * V init(A); 4467 * V body(int, V, A); 4468 * V countedLoop(A a) { 4469 * int s = start(a); 4470 * int e = end(a); 4471 * V v = init(a); 4472 * for (int i = s; i < e; ++i) { 4473 * v = body(i, v, a); 4474 * } 4475 * return v; 4476 * } 4477 * }</pre></blockquote> 4478 * 4479 * <p> 4480 * @implSpec The implementation of this method is equivalent to: 4481 * <blockquote><pre>{@code 4482 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4483 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 4484 * // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int, 4485 * // assume MH_decrement is a handle to x-1 of type int 4486 * MethodHandle[] 4487 * indexVar = {start, MH_increment}, // i = start; i = i+1 4488 * loopLimit = {end, null, MH_lessThan, returnVar }, // i<end 4489 * bodyClause = {init, 4490 * filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v) 4491 * return loop(indexVar, loopLimit, bodyClause); 4492 * } 4493 * }</pre></blockquote> 4494 * 4495 * @param start a handle to return the start value of the loop counter. 4496 * If it is {@code null}, a constant zero is assumed. 4497 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}). 4498 * @param init initializer for additional loop state. This determines the loop's result type. 4499 * Passing {@code null} or a {@code void} init function will make the loop's result type 4500 * {@code void}. 4501 * @param body the body of the loop, which must not be {@code null}. 4502 * It must accept an initial {@code int} parameter (for the counter), and then any 4503 * additional loop-local variable plus loop parameters. 4504 * 4505 * @return a method handle representing the loop. 4506 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4507 * 4508 * @since 9 4509 */ 4510 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4511 Class<?> resultType; 4512 MethodHandle actualInit; 4513 if (init == null) { 4514 resultType = body == null ? void.class : body.type().returnType(); 4515 actualInit = empty(methodType(resultType)); 4516 } else { 4517 resultType = init.type().returnType(); 4518 actualInit = init; 4519 } 4520 MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType); 4521 MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body; 4522 MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class); 4523 MethodHandle actualEnd = end == null ? constant(int.class, 0) : end; 4524 MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)}; 4525 MethodHandle[] loopLimit = {actualEnd, null, 4526 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar}; 4527 MethodHandle[] bodyClause = {actualInit, 4528 filterArgument(dropArguments(actualBody, 1, int.class), 0, 4529 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter))}; 4530 return loop(indexVar, loopLimit, bodyClause); 4531 } 4532 4533 /** 4534 * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}. 4535 * The iterator will be produced by the evaluation of the {@code iterator} handle. 4536 * This handle must have {@link java.util.Iterator} as its return type. 4537 * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead, 4538 * and will be applied to a leading argument of the loop handle. 4539 * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter. 4540 * The result of the loop execution is the final value of the additional local state 4541 * obtained by running {@code init}. 4542 * <p> 4543 * This is a convenience wrapper for the 4544 * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body} 4545 * handle follow directly from those described for the latter. 4546 * <p> 4547 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4548 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 4549 * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop. 4550 * <blockquote><pre>{@code 4551 * Iterator<T> iterator(A); // defaults to Iterable::iterator 4552 * V init(A); 4553 * V body(T,V,A); 4554 * V iteratedLoop(A a) { 4555 * Iterator<T> it = iterator(a); 4556 * V v = init(a); 4557 * for (T t : it) { 4558 * v = body(t, v, a); 4559 * } 4560 * return v; 4561 * } 4562 * }</pre></blockquote> 4563 * <p> 4564 * The type {@code T} may be either a primitive or reference. 4565 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type 4566 * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} 4567 * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method. 4568 * Therefore, if an iterator of the wrong type appears as the loop is executed, 4569 * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}. 4570 * <p> 4571 * @apiNote Example: 4572 * <blockquote><pre>{@code 4573 * // reverse a list 4574 * static List<String> reverseStep(String e, List<String> r, List<String> l) { 4575 * r.add(0, e); 4576 * return r; 4577 * } 4578 * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); } 4579 * // assume MH_reverseStep, MH_newArrayList are handles to the above methods 4580 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 4581 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 4582 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 4583 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 4584 * }</pre></blockquote> 4585 * <p> 4586 * @implSpec The implementation of this method is equivalent to (excluding error handling): 4587 * <blockquote><pre>{@code 4588 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 4589 * // assume MH_next and MH_hasNext are handles to methods of Iterator 4590 * Class<?> itype = iterator.type().returnType(); 4591 * Class<?> ttype = body.type().parameterType(0); 4592 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype); 4593 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 4594 * MethodHandle[] 4595 * iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext) 4596 * bodyClause = {init, filterArgument(body, 0, nextVal)}; // v = body(t, v, a); 4597 * return loop(iterVar, bodyClause); 4598 * } 4599 * }</pre></blockquote> 4600 * 4601 * @param iterator a handle to return the iterator to start the loop. 4602 * The handle must have {@link java.util.Iterator} as its return type. 4603 * Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first 4604 * incoming value. 4605 * @param init initializer for additional loop state. This determines the loop's result type. 4606 * Passing {@code null} or a {@code void} init function will make the loop's result type 4607 * {@code void}. 4608 * @param body the body of the loop, which must not be {@code null}. 4609 * It must accept an initial {@code T} parameter (for the iterated values), and then any 4610 * additional loop-local variable plus loop parameters. 4611 * 4612 * @return a method handle embodying the iteration loop functionality. 4613 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4614 * 4615 * @since 9 4616 */ 4617 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 4618 checkIteratedLoop(iterator, body); 4619 Class<?> resultType = init == null ? 4620 body == null ? void.class : body.type().returnType() : 4621 init.type().returnType(); 4622 boolean voidResult = resultType == void.class; 4623 4624 MethodHandle initIterator; 4625 if (iterator == null) { 4626 MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 4627 initIterator = initit.asType(initit.type().changeParameterType(0, 4628 body.type().parameterType(voidResult ? 1 : 2))); 4629 } else { 4630 initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class)); 4631 } 4632 4633 Class<?> ttype = body.type().parameterType(0); 4634 4635 MethodHandle returnVar = 4636 dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class); 4637 MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 4638 MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype)); 4639 4640 MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred), 4641 returnVar}; 4642 MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)}; 4643 4644 return loop(iterVar, bodyClause); 4645 } 4646 4647 /** 4648 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 4649 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 4650 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 4651 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 4652 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 4653 * {@code try-finally} handle. 4654 * <p> 4655 * The {@code cleanup} handle will be passed one or two additional leading arguments. 4656 * The first is the exception thrown during the 4657 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 4658 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 4659 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 4660 * The second argument is not present if the {@code target} handle has a {@code void} return type. 4661 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 4662 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 4663 * <p> 4664 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 4665 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 4666 * two extra leading parameters:<ul> 4667 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 4668 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 4669 * the result from the execution of the {@code target} handle. 4670 * This parameter is not present if the {@code target} returns {@code void}. 4671 * </ul> 4672 * <p> 4673 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 4674 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 4675 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 4676 * the cleanup. 4677 * <blockquote><pre>{@code 4678 * V target(A..., B...); 4679 * V cleanup(Throwable, V, A...); 4680 * V adapter(A... a, B... b) { 4681 * V result = (zero value for V); 4682 * Throwable throwable = null; 4683 * try { 4684 * result = target(a..., b...); 4685 * } catch (Throwable t) { 4686 * throwable = t; 4687 * throw t; 4688 * } finally { 4689 * result = cleanup(throwable, result, a...); 4690 * } 4691 * return result; 4692 * } 4693 * }</pre></blockquote> 4694 * <p> 4695 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 4696 * be modified by execution of the target, and so are passed unchanged 4697 * from the caller to the cleanup, if it is invoked. 4698 * <p> 4699 * The target and cleanup must return the same type, even if the cleanup 4700 * always throws. 4701 * To create such a throwing cleanup, compose the cleanup logic 4702 * with {@link #throwException throwException}, 4703 * in order to create a method handle of the correct return type. 4704 * <p> 4705 * Note that {@code tryFinally} never converts exceptions into normal returns. 4706 * In rare cases where exceptions must be converted in that way, first wrap 4707 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 4708 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 4709 * 4710 * @param target the handle whose execution is to be wrapped in a {@code try} block. 4711 * @param cleanup the handle that is invoked in the finally block. 4712 * 4713 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 4714 * @throws NullPointerException if any argument is null 4715 * @throws IllegalArgumentException if {@code cleanup} does not accept 4716 * the required leading arguments, or if the method handle types do 4717 * not match in their return types and their 4718 * corresponding trailing parameters 4719 * 4720 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 4721 * @since 9 4722 */ 4723 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 4724 List<Class<?>> targetParamTypes = target.type().parameterList(); 4725 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); 4726 Class<?> rtype = target.type().returnType(); 4727 4728 checkTryFinally(target, cleanup); 4729 4730 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 4731 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 4732 // target parameter list. 4733 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); 4734 MethodHandle aTarget = target.asSpreader(Object[].class, target.type().parameterCount()); 4735 MethodHandle aCleanup = cleanup.asSpreader(Object[].class, targetParamTypes.size()); 4736 4737 return MethodHandleImpl.makeTryFinally(aTarget, aCleanup, rtype, targetParamTypes); 4738 } 4739 4740 /** 4741 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 4742 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 4743 * before the folded arguments. 4744 * <p> 4745 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 4746 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 4747 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 4748 * 0. 4749 * <p> 4750 * @apiNote Example: 4751 * <blockquote><pre>{@code 4752 import static java.lang.invoke.MethodHandles.*; 4753 import static java.lang.invoke.MethodType.*; 4754 ... 4755 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 4756 "println", methodType(void.class, String.class)) 4757 .bindTo(System.out); 4758 MethodHandle cat = lookup().findVirtual(String.class, 4759 "concat", methodType(String.class, String.class)); 4760 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 4761 MethodHandle catTrace = foldArguments(cat, 1, trace); 4762 // also prints "jum": 4763 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 4764 * }</pre></blockquote> 4765 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 4766 * represents the result type of the {@code target} and resulting adapter. 4767 * {@code V}/{@code v} represent the type and value of the parameter and argument 4768 * of {@code target} that precedes the folding position; {@code V} also is 4769 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 4770 * types and values of the {@code N} parameters and arguments at the folding 4771 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 4772 * and values of the {@code target} parameters and arguments that precede and 4773 * follow the folded parameters and arguments starting at {@code pos}, 4774 * respectively. 4775 * <blockquote><pre>{@code 4776 * // there are N arguments in A... 4777 * T target(Z..., V, A[N]..., B...); 4778 * V combiner(A...); 4779 * T adapter(Z... z, A... a, B... b) { 4780 * V v = combiner(a...); 4781 * return target(z..., v, a..., b...); 4782 * } 4783 * // and if the combiner has a void return: 4784 * T target2(Z..., A[N]..., B...); 4785 * void combiner2(A...); 4786 * T adapter2(Z... z, A... a, B... b) { 4787 * combiner2(a...); 4788 * return target2(z..., a..., b...); 4789 * } 4790 * }</pre></blockquote> 4791 * <p> 4792 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4793 * variable-arity method handle}, even if the original target method handle was. 4794 * 4795 * @param target the method handle to invoke after arguments are combined 4796 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 4797 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 4798 * @param combiner method handle to call initially on the incoming arguments 4799 * @return method handle which incorporates the specified argument folding logic 4800 * @throws NullPointerException if either argument is null 4801 * @throws IllegalArgumentException if {@code combiner}'s return type 4802 * is non-void and not the same as the argument type at position {@code pos} of 4803 * the target signature, or if the {@code N} argument types at position {@code pos} 4804 * of the target signature 4805 * (skipping one matching the {@code combiner}'s return type) 4806 * are not identical with the argument types of {@code combiner} 4807 * 4808 * @see #foldArguments(MethodHandle, MethodHandle) 4809 * @since 9 4810 */ 4811 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 4812 MethodType targetType = target.type(); 4813 MethodType combinerType = combiner.type(); 4814 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 4815 BoundMethodHandle result = target.rebind(); 4816 boolean dropResult = rtype == void.class; 4817 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 4818 MethodType newType = targetType; 4819 if (!dropResult) { 4820 newType = newType.dropParameterTypes(pos, pos + 1); 4821 } 4822 result = result.copyWithExtendL(newType, lform, combiner); 4823 return result; 4824 } 4825 4826 4827 private static void checkLoop0(MethodHandle[][] clauses) { 4828 if (clauses == null || clauses.length == 0) { 4829 throw newIllegalArgumentException("null or no clauses passed"); 4830 } 4831 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 4832 throw newIllegalArgumentException("null clauses are not allowed"); 4833 } 4834 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 4835 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 4836 } 4837 } 4838 4839 private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) { 4840 if (in.type().returnType() != st.type().returnType()) { 4841 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 4842 st.type().returnType()); 4843 } 4844 } 4845 4846 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 4847 final List<Class<?>> empty = List.of(); 4848 final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList()); 4849 if (nonNullInits.isEmpty()) { 4850 final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull). 4851 // take only those that can contribute to a common suffix because they are longer than the prefix 4852 map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList). 4853 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 4854 return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size()); 4855 } else { 4856 return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList). 4857 reduce((p, q) -> p.size() >= q.size() ? p : q).get(); 4858 } 4859 } 4860 4861 private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 4862 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList). 4863 anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) { 4864 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 4865 " (common suffix: " + commonSuffix + ")"); 4866 } 4867 } 4868 4869 private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 4870 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4871 anyMatch(t -> t != loopReturnType)) { 4872 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 4873 loopReturnType + ")"); 4874 } 4875 4876 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { 4877 throw newIllegalArgumentException("no predicate found", pred); 4878 } 4879 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4880 anyMatch(t -> t != boolean.class)) { 4881 throw newIllegalArgumentException("predicates must have boolean return type", pred); 4882 } 4883 } 4884 4885 private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 4886 final int cpSize = commonParameterSequence.size(); 4887 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 4888 map(MethodType::parameterList). 4889 anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) { 4890 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 4891 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 4892 } 4893 } 4894 4895 private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) { 4896 if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) { 4897 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 4898 } 4899 if (null == body) { 4900 throw newIllegalArgumentException("iterated loop body must not be null"); 4901 } 4902 } 4903 4904 private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) { 4905 Class<?> rtype = target.type().returnType(); 4906 if (rtype != cleanup.type().returnType()) { 4907 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 4908 } 4909 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); 4910 if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) { 4911 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 4912 } 4913 if (rtype != void.class && cleanupParamTypes.get(1) != rtype) { 4914 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 4915 } 4916 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 4917 // target parameter list. 4918 int cleanupArgIndex = rtype == void.class ? 1 : 2; 4919 List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size()); 4920 List<Class<?>> targetParamTypes = target.type().parameterList(); 4921 if (targetParamTypes.size() < cleanupArgSuffix.size() || 4922 !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) { 4923 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 4924 cleanup.type(), target.type()); 4925 } 4926 } 4927 4928 }