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