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