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