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