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