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