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