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