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