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