1 /* 2 * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.misc.SharedSecrets; 29 import jdk.internal.module.IllegalAccessLogger; 30 import jdk.internal.org.objectweb.asm.ClassReader; 31 import jdk.internal.reflect.CallerSensitive; 32 import jdk.internal.reflect.Reflection; 33 import jdk.internal.vm.annotation.ForceInline; 34 import sun.invoke.util.ValueConversions; 35 import sun.invoke.util.VerifyAccess; 36 import sun.invoke.util.Wrapper; 37 import sun.reflect.misc.ReflectUtil; 38 import sun.security.util.SecurityConstants; 39 40 import java.lang.invoke.LambdaForm.BasicType; 41 import java.lang.reflect.Constructor; 42 import java.lang.reflect.Field; 43 import java.lang.reflect.Member; 44 import java.lang.reflect.Method; 45 import java.lang.reflect.Modifier; 46 import java.lang.reflect.ReflectPermission; 47 import java.nio.ByteOrder; 48 import java.security.AccessController; 49 import java.security.PrivilegedAction; 50 import java.security.ProtectionDomain; 51 import java.util.ArrayList; 52 import java.util.Arrays; 53 import java.util.BitSet; 54 import java.util.Iterator; 55 import java.util.List; 56 import java.util.Objects; 57 import java.util.concurrent.ConcurrentHashMap; 58 import java.util.stream.Collectors; 59 import java.util.stream.Stream; 60 61 import static java.lang.invoke.MethodHandleImpl.Intrinsic; 62 import static java.lang.invoke.MethodHandleNatives.Constants.*; 63 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 64 import static java.lang.invoke.MethodType.methodType; 65 66 /** 67 * This class consists exclusively of static methods that operate on or return 68 * method handles. They fall into several categories: 69 * <ul> 70 * <li>Lookup methods which help create method handles for methods and fields. 71 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 72 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 73 * </ul> 74 * 75 * @author John Rose, JSR 292 EG 76 * @since 1.7 77 */ 78 public class MethodHandles { 79 80 private MethodHandles() { } // do not instantiate 81 82 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 83 84 // See IMPL_LOOKUP below. 85 86 //// Method handle creation from ordinary methods. 87 88 /** 89 * Returns a {@link Lookup lookup object} with 90 * full capabilities to emulate all supported bytecode behaviors of the caller. 91 * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller. 92 * Factory methods on the lookup object can create 93 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 94 * for any member that the caller has access to via bytecodes, 95 * including protected and private fields and methods. 96 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 97 * Do not store it in place where untrusted code can access it. 98 * <p> 99 * This method is caller sensitive, which means that it may return different 100 * values to different callers. 101 * @return a lookup object for the caller of this method, with private access 102 */ 103 @CallerSensitive 104 @ForceInline // to ensure Reflection.getCallerClass optimization 105 public static Lookup lookup() { 106 return new Lookup(Reflection.getCallerClass()); 107 } 108 109 /** 110 * This reflected$lookup method is the alternate implementation of 111 * the lookup method when being invoked by reflection. 112 */ 113 @CallerSensitive 114 private static Lookup reflected$lookup() { 115 Class<?> caller = Reflection.getCallerClass(); 116 if (caller.getClassLoader() == null) { 117 throw newIllegalArgumentException("illegal lookupClass: "+caller); 118 } 119 return new Lookup(caller); 120 } 121 122 /** 123 * Returns a {@link Lookup lookup object} which is trusted minimally. 124 * The lookup has the {@code PUBLIC} and {@code UNCONDITIONAL} modes. 125 * It can only be used to create method handles to public members of 126 * public classes in packages that are exported unconditionally. 127 * <p> 128 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 129 * of this lookup object will be {@link java.lang.Object}. 130 * 131 * @apiNote The use of Object is conventional, and because the lookup modes are 132 * limited, there is no special access provided to the internals of Object, its package 133 * or its module. Consequently, the lookup context of this lookup object will be the 134 * bootstrap class loader, which means it cannot find user classes. 135 * 136 * <p style="font-size:smaller;"> 137 * <em>Discussion:</em> 138 * The lookup class can be changed to any other class {@code C} using an expression of the form 139 * {@link Lookup#in publicLookup().in(C.class)}. 140 * but may change the lookup context by virtue of changing the class loader. 141 * A public lookup object is always subject to 142 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 143 * Also, it cannot access 144 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 145 * @return a lookup object which is trusted minimally 146 * 147 * @revised 9 148 * @spec JPMS 149 */ 150 public static Lookup publicLookup() { 151 return Lookup.PUBLIC_LOOKUP; 152 } 153 154 /** 155 * Returns a {@link Lookup lookup object} with full capabilities to emulate all 156 * supported bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc"> 157 * private access</a>, on a target class. 158 * This method checks that a caller, specified as a {@code Lookup} object, is allowed to 159 * do <em>deep reflection</em> on the target class. If {@code m1} is the module containing 160 * the {@link Lookup#lookupClass() lookup class}, and {@code m2} is the module containing 161 * the target class, then this check ensures that 162 * <ul> 163 * <li>{@code m1} {@link Module#canRead reads} {@code m2}.</li> 164 * <li>{@code m2} {@link Module#isOpen(String,Module) opens} the package containing 165 * the target class to at least {@code m1}.</li> 166 * <li>The lookup has the {@link Lookup#MODULE MODULE} lookup mode.</li> 167 * </ul> 168 * <p> 169 * If there is a security manager, its {@code checkPermission} method is called to 170 * check {@code ReflectPermission("suppressAccessChecks")}. 171 * @apiNote The {@code MODULE} lookup mode serves to authenticate that the lookup object 172 * was created by code in the caller module (or derived from a lookup object originally 173 * created by the caller). A lookup object with the {@code MODULE} lookup mode can be 174 * shared with trusted parties without giving away {@code PRIVATE} and {@code PACKAGE} 175 * access to the caller. 176 * @param targetClass the target class 177 * @param lookup the caller lookup object 178 * @return a lookup object for the target class, with private access 179 * @throws IllegalArgumentException if {@code targetClass} is a primitve type or array class 180 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 181 * @throws IllegalAccessException if the access check specified above fails 182 * @throws SecurityException if denied by the security manager 183 * @since 9 184 * @spec JPMS 185 * @see Lookup#dropLookupMode 186 */ 187 public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException { 188 SecurityManager sm = System.getSecurityManager(); 189 if (sm != null) sm.checkPermission(ACCESS_PERMISSION); 190 if (targetClass.isPrimitive()) 191 throw new IllegalArgumentException(targetClass + " is a primitive class"); 192 if (targetClass.isArray()) 193 throw new IllegalArgumentException(targetClass + " is an array class"); 194 Module targetModule = targetClass.getModule(); 195 Module callerModule = lookup.lookupClass().getModule(); 196 if (!callerModule.canRead(targetModule)) 197 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 198 if (targetModule.isNamed()) { 199 String pn = targetClass.getPackageName(); 200 assert !pn.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 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 703 private static int fixmods(int mods) { 704 mods &= (ALL_MODES - PACKAGE - MODULE - UNCONDITIONAL); 705 return (mods != 0) ? mods : (PACKAGE | MODULE | UNCONDITIONAL); 706 } 707 708 /** Tells which class is performing the lookup. It is this class against 709 * which checks are performed for visibility and access permissions. 710 * <p> 711 * The class implies a maximum level of access permission, 712 * but the permissions may be additionally limited by the bitmask 713 * {@link #lookupModes lookupModes}, which controls whether non-public members 714 * can be accessed. 715 * @return the lookup class, on behalf of which this lookup object finds members 716 */ 717 public Class<?> lookupClass() { 718 return lookupClass; 719 } 720 721 // This is just for calling out to MethodHandleImpl. 722 private Class<?> lookupClassOrNull() { 723 return (allowedModes == TRUSTED) ? null : lookupClass; 724 } 725 726 /** Tells which access-protection classes of members this lookup object can produce. 727 * The result is a bit-mask of the bits 728 * {@linkplain #PUBLIC PUBLIC (0x01)}, 729 * {@linkplain #PRIVATE PRIVATE (0x02)}, 730 * {@linkplain #PROTECTED PROTECTED (0x04)}, 731 * {@linkplain #PACKAGE PACKAGE (0x08)}, 732 * {@linkplain #MODULE MODULE (0x10)}, 733 * and {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}. 734 * <p> 735 * A freshly-created lookup object 736 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 737 * all possible bits set, except {@code UNCONDITIONAL}. 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 */ 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 */ 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 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 */ 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 */ 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 */ 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 969 private ProtectionDomain lookupClassProtectionDomain() { 970 ProtectionDomain pd = cachedProtectionDomain; 971 if (pd == null) { 972 cachedProtectionDomain = pd = protectionDomain(lookupClass); 973 } 974 return pd; 975 } 976 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. 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 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 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 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, findBoundCallerClass(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 */ 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, findBoundCallerClass(method)); 1196 } 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 } 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 */ 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 */ 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 */ 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 */ 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, findBoundCallerClass(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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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, findBoundCallerClass(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 */ 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, findBoundCallerClass(method)); 1748 } 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 } 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 */ 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, findBoundCallerClass(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 */ 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 */ 1851 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 1852 return unreflectField(f, false); 1853 } 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 */ 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 */ 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 */ 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 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 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 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 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 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 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. */ 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 */ 2076 Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException { 2077 Class<?> callerClass = null; 2078 if (MethodHandleNatives.isCallerSensitive(m)) { 2079 // Only lookups with private access are allowed to resolve caller-sensitive methods 2080 if (hasPrivateAccess()) { 2081 callerClass = lookupClass; 2082 } else { 2083 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 2084 } 2085 } 2086 return callerClass; 2087 } 2088 2089 /** 2090 * Returns {@code true} if this lookup has {@code PRIVATE} access. 2091 * @return {@code true} if this lookup has {@code PRIVATE} access. 2092 * @since 9 2093 */ 2094 public boolean hasPrivateAccess() { 2095 return (allowedModes & PRIVATE) != 0; 2096 } 2097 2098 /** 2099 * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 2100 * Determines a trustable caller class to compare with refc, the symbolic reference class. 2101 * If this lookup object has private access, then the caller class is the lookupClass. 2102 */ 2103 void checkSecurityManager(Class<?> refc, MemberName m) { 2104 SecurityManager smgr = System.getSecurityManager(); 2105 if (smgr == null) return; 2106 if (allowedModes == TRUSTED) return; 2107 2108 // Step 1: 2109 boolean fullPowerLookup = hasPrivateAccess(); 2110 if (!fullPowerLookup || 2111 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 2112 ReflectUtil.checkPackageAccess(refc); 2113 } 2114 2115 if (m == null) { // findClass or accessClass 2116 // Step 2b: 2117 if (!fullPowerLookup) { 2118 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 2119 } 2120 return; 2121 } 2122 2123 // Step 2a: 2124 if (m.isPublic()) return; 2125 if (!fullPowerLookup) { 2126 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 2127 } 2128 2129 // Step 3: 2130 Class<?> defc = m.getDeclaringClass(); 2131 if (!fullPowerLookup && defc != refc) { 2132 ReflectUtil.checkPackageAccess(defc); 2133 } 2134 } 2135 2136 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 2137 boolean wantStatic = (refKind == REF_invokeStatic); 2138 String message; 2139 if (m.isConstructor()) 2140 message = "expected a method, not a constructor"; 2141 else if (!m.isMethod()) 2142 message = "expected a method"; 2143 else if (wantStatic != m.isStatic()) 2144 message = wantStatic ? "expected a static method" : "expected a non-static method"; 2145 else 2146 { checkAccess(refKind, refc, m); return; } 2147 throw m.makeAccessException(message, this); 2148 } 2149 2150 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 2151 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 2152 String message; 2153 if (wantStatic != m.isStatic()) 2154 message = wantStatic ? "expected a static field" : "expected a non-static field"; 2155 else 2156 { checkAccess(refKind, refc, m); return; } 2157 throw m.makeAccessException(message, this); 2158 } 2159 2160 /** Check public/protected/private bits on the symbolic reference class and its member. */ 2161 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 2162 assert(m.referenceKindIsConsistentWith(refKind) && 2163 MethodHandleNatives.refKindIsValid(refKind) && 2164 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 2165 int allowedModes = this.allowedModes; 2166 if (allowedModes == TRUSTED) return; 2167 int mods = m.getModifiers(); 2168 if (Modifier.isProtected(mods) && 2169 refKind == REF_invokeVirtual && 2170 m.getDeclaringClass() == Object.class && 2171 m.getName().equals("clone") && 2172 refc.isArray()) { 2173 // The JVM does this hack also. 2174 // (See ClassVerifier::verify_invoke_instructions 2175 // and LinkResolver::check_method_accessability.) 2176 // Because the JVM does not allow separate methods on array types, 2177 // there is no separate method for int[].clone. 2178 // All arrays simply inherit Object.clone. 2179 // But for access checking logic, we make Object.clone 2180 // (normally protected) appear to be public. 2181 // Later on, when the DirectMethodHandle is created, 2182 // its leading argument will be restricted to the 2183 // requested array type. 2184 // N.B. The return type is not adjusted, because 2185 // that is *not* the bytecode behavior. 2186 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 2187 } 2188 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 2189 // cannot "new" a protected ctor in a different package 2190 mods ^= Modifier.PROTECTED; 2191 } 2192 if (Modifier.isFinal(mods) && 2193 MethodHandleNatives.refKindIsSetter(refKind)) 2194 throw m.makeAccessException("unexpected set of a final field", this); 2195 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 2196 if ((requestedModes & allowedModes) != 0) { 2197 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 2198 mods, lookupClass(), allowedModes)) 2199 return; 2200 } else { 2201 // Protected members can also be checked as if they were package-private. 2202 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 2203 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 2204 return; 2205 } 2206 throw m.makeAccessException(accessFailedMessage(refc, m), this); 2207 } 2208 2209 String accessFailedMessage(Class<?> refc, MemberName m) { 2210 Class<?> defc = m.getDeclaringClass(); 2211 int mods = m.getModifiers(); 2212 // check the class first: 2213 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 2214 (defc == refc || 2215 Modifier.isPublic(refc.getModifiers()))); 2216 if (!classOK && (allowedModes & PACKAGE) != 0) { 2217 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), FULL_POWER_MODES) && 2218 (defc == refc || 2219 VerifyAccess.isClassAccessible(refc, lookupClass(), FULL_POWER_MODES))); 2220 } 2221 if (!classOK) 2222 return "class is not public"; 2223 if (Modifier.isPublic(mods)) 2224 return "access to public member failed"; // (how?, module not readable?) 2225 if (Modifier.isPrivate(mods)) 2226 return "member is private"; 2227 if (Modifier.isProtected(mods)) 2228 return "member is protected"; 2229 return "member is private to package"; 2230 } 2231 2232 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 2233 int allowedModes = this.allowedModes; 2234 if (allowedModes == TRUSTED) return; 2235 if (!hasPrivateAccess() 2236 || (specialCaller != lookupClass() 2237 // ensure non-abstract methods in superinterfaces can be special-invoked 2238 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 2239 throw new MemberName(specialCaller). 2240 makeAccessException("no private access for invokespecial", this); 2241 } 2242 2243 private boolean restrictProtectedReceiver(MemberName method) { 2244 // The accessing class only has the right to use a protected member 2245 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 2246 if (!method.isProtected() || method.isStatic() 2247 || allowedModes == TRUSTED 2248 || method.getDeclaringClass() == lookupClass() 2249 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 2250 return false; 2251 return true; 2252 } 2253 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 2254 assert(!method.isStatic()); 2255 // receiver type of mh is too wide; narrow to caller 2256 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 2257 throw method.makeAccessException("caller class must be a subclass below the method", caller); 2258 } 2259 MethodType rawType = mh.type(); 2260 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 2261 MethodType narrowType = rawType.changeParameterType(0, caller); 2262 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 2263 assert(mh.viewAsTypeChecks(narrowType, true)); 2264 return mh.copyWith(narrowType, mh.form); 2265 } 2266 2267 /** Check access and get the requested method. */ 2268 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> boundCallerClass) throws IllegalAccessException { 2269 final boolean doRestrict = true; 2270 final boolean checkSecurity = true; 2271 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, boundCallerClass); 2272 } 2273 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 2274 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Class<?> boundCallerClass) throws IllegalAccessException { 2275 final boolean doRestrict = false; 2276 final boolean checkSecurity = true; 2277 return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, boundCallerClass); 2278 } 2279 /** Check access and get the requested method, eliding security manager checks. */ 2280 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> boundCallerClass) throws IllegalAccessException { 2281 final boolean doRestrict = true; 2282 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2283 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, boundCallerClass); 2284 } 2285 /** Common code for all methods; do not call directly except from immediately above. */ 2286 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 2287 boolean checkSecurity, 2288 boolean doRestrict, Class<?> boundCallerClass) throws IllegalAccessException { 2289 2290 checkMethod(refKind, refc, method); 2291 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2292 if (checkSecurity) 2293 checkSecurityManager(refc, method); 2294 assert(!method.isMethodHandleInvoke()); 2295 2296 if (refKind == REF_invokeSpecial && 2297 refc != lookupClass() && 2298 !refc.isInterface() && 2299 refc != lookupClass().getSuperclass() && 2300 refc.isAssignableFrom(lookupClass())) { 2301 assert(!method.getName().equals("<init>")); // not this code path 2302 2303 // Per JVMS 6.5, desc. of invokespecial instruction: 2304 // If the method is in a superclass of the LC, 2305 // and if our original search was above LC.super, 2306 // repeat the search (symbolic lookup) from LC.super 2307 // and continue with the direct superclass of that class, 2308 // and so forth, until a match is found or no further superclasses exist. 2309 // FIXME: MemberName.resolve should handle this instead. 2310 Class<?> refcAsSuper = lookupClass(); 2311 MemberName m2; 2312 do { 2313 refcAsSuper = refcAsSuper.getSuperclass(); 2314 m2 = new MemberName(refcAsSuper, 2315 method.getName(), 2316 method.getMethodType(), 2317 REF_invokeSpecial); 2318 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); 2319 } while (m2 == null && // no method is found yet 2320 refc != refcAsSuper); // search up to refc 2321 if (m2 == null) throw new InternalError(method.toString()); 2322 method = m2; 2323 refc = refcAsSuper; 2324 // redo basic checks 2325 checkMethod(refKind, refc, method); 2326 } 2327 2328 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 2329 MethodHandle mh = dmh; 2330 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 2331 if ((doRestrict && refKind == REF_invokeSpecial) || 2332 (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) { 2333 mh = restrictReceiver(method, dmh, lookupClass()); 2334 } 2335 mh = maybeBindCaller(method, mh, boundCallerClass); 2336 mh = mh.setVarargs(method); 2337 return mh; 2338 } 2339 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, 2340 Class<?> boundCallerClass) 2341 throws IllegalAccessException { 2342 if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 2343 return mh; 2344 Class<?> hostClass = lookupClass; 2345 if (!hasPrivateAccess()) // caller must have private access 2346 hostClass = boundCallerClass; // boundCallerClass came from a security manager style stack walk 2347 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); 2348 // Note: caller will apply varargs after this step happens. 2349 return cbmh; 2350 } 2351 /** Check access and get the requested field. */ 2352 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 2353 final boolean checkSecurity = true; 2354 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2355 } 2356 /** Check access and get the requested field, eliding security manager checks. */ 2357 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 2358 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2359 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2360 } 2361 /** Common code for all fields; do not call directly except from immediately above. */ 2362 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 2363 boolean checkSecurity) throws IllegalAccessException { 2364 checkField(refKind, refc, field); 2365 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2366 if (checkSecurity) 2367 checkSecurityManager(refc, field); 2368 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 2369 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 2370 restrictProtectedReceiver(field)); 2371 if (doRestrict) 2372 return restrictReceiver(field, dmh, lookupClass()); 2373 return dmh; 2374 } 2375 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 2376 Class<?> refc, MemberName getField, MemberName putField) 2377 throws IllegalAccessException { 2378 final boolean checkSecurity = true; 2379 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2380 } 2381 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 2382 Class<?> refc, MemberName getField, MemberName putField) 2383 throws IllegalAccessException { 2384 final boolean checkSecurity = false; 2385 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2386 } 2387 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 2388 Class<?> refc, MemberName getField, MemberName putField, 2389 boolean checkSecurity) throws IllegalAccessException { 2390 assert getField.isStatic() == putField.isStatic(); 2391 assert getField.isGetter() && putField.isSetter(); 2392 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 2393 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 2394 2395 checkField(getRefKind, refc, getField); 2396 if (checkSecurity) 2397 checkSecurityManager(refc, getField); 2398 2399 if (!putField.isFinal()) { 2400 // A VarHandle does not support updates to final fields, any 2401 // such VarHandle to a final field will be read-only and 2402 // therefore the following write-based accessibility checks are 2403 // only required for non-final fields 2404 checkField(putRefKind, refc, putField); 2405 if (checkSecurity) 2406 checkSecurityManager(refc, putField); 2407 } 2408 2409 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 2410 restrictProtectedReceiver(getField)); 2411 if (doRestrict) { 2412 assert !getField.isStatic(); 2413 // receiver type of VarHandle is too wide; narrow to caller 2414 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 2415 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 2416 } 2417 refc = lookupClass(); 2418 } 2419 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED); 2420 } 2421 /** Check access and get the requested constructor. */ 2422 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2423 final boolean checkSecurity = true; 2424 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2425 } 2426 /** Check access and get the requested constructor, eliding security manager checks. */ 2427 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2428 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2429 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2430 } 2431 /** Common code for all constructors; do not call directly except from immediately above. */ 2432 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 2433 boolean checkSecurity) throws IllegalAccessException { 2434 assert(ctor.isConstructor()); 2435 checkAccess(REF_newInvokeSpecial, refc, ctor); 2436 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2437 if (checkSecurity) 2438 checkSecurityManager(refc, ctor); 2439 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 2440 return DirectMethodHandle.make(ctor).setVarargs(ctor); 2441 } 2442 2443 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 2444 */ 2445 /*non-public*/ 2446 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { 2447 if (!(type instanceof Class || type instanceof MethodType)) 2448 throw new InternalError("unresolved MemberName"); 2449 MemberName member = new MemberName(refKind, defc, name, type); 2450 MethodHandle mh = LOOKASIDE_TABLE.get(member); 2451 if (mh != null) { 2452 checkSymbolicClass(defc); 2453 return mh; 2454 } 2455 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 2456 // Treat MethodHandle.invoke and invokeExact specially. 2457 mh = findVirtualForMH(member.getName(), member.getMethodType()); 2458 if (mh != null) { 2459 return mh; 2460 } 2461 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 2462 // Treat signature-polymorphic methods on VarHandle specially. 2463 mh = findVirtualForVH(member.getName(), member.getMethodType()); 2464 if (mh != null) { 2465 return mh; 2466 } 2467 } 2468 MemberName resolved = resolveOrFail(refKind, member); 2469 mh = getDirectMethodForConstant(refKind, defc, resolved); 2470 if (mh instanceof DirectMethodHandle 2471 && canBeCached(refKind, defc, resolved)) { 2472 MemberName key = mh.internalMemberName(); 2473 if (key != null) { 2474 key = key.asNormalOriginal(); 2475 } 2476 if (member.equals(key)) { // better safe than sorry 2477 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 2478 } 2479 } 2480 return mh; 2481 } 2482 private 2483 boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 2484 if (refKind == REF_invokeSpecial) { 2485 return false; 2486 } 2487 if (!Modifier.isPublic(defc.getModifiers()) || 2488 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 2489 !member.isPublic() || 2490 member.isCallerSensitive()) { 2491 return false; 2492 } 2493 ClassLoader loader = defc.getClassLoader(); 2494 if (loader != null) { 2495 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 2496 boolean found = false; 2497 while (sysl != null) { 2498 if (loader == sysl) { found = true; break; } 2499 sysl = sysl.getParent(); 2500 } 2501 if (!found) { 2502 return false; 2503 } 2504 } 2505 try { 2506 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 2507 new MemberName(refKind, defc, member.getName(), member.getType())); 2508 if (resolved2 == null) { 2509 return false; 2510 } 2511 checkSecurityManager(defc, resolved2); 2512 } catch (SecurityException ex) { 2513 return false; 2514 } 2515 return true; 2516 } 2517 private 2518 MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 2519 throws ReflectiveOperationException { 2520 if (MethodHandleNatives.refKindIsField(refKind)) { 2521 return getDirectFieldNoSecurityManager(refKind, defc, member); 2522 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 2523 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); 2524 } else if (refKind == REF_newInvokeSpecial) { 2525 return getDirectConstructorNoSecurityManager(defc, member); 2526 } 2527 // oops 2528 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 2529 } 2530 2531 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 2532 } 2533 2534 /** 2535 * Produces a method handle constructing arrays of a desired type, 2536 * as if by the {@code anewarray} bytecode. 2537 * The return type of the method handle will be the array type. 2538 * The type of its sole argument will be {@code int}, which specifies the size of the array. 2539 * 2540 * <p> If the returned method handle is invoked with a negative 2541 * array size, a {@code NegativeArraySizeException} will be thrown. 2542 * 2543 * @param arrayClass an array type 2544 * @return a method handle which can create arrays of the given type 2545 * @throws NullPointerException if the argument is {@code null} 2546 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 2547 * @see java.lang.reflect.Array#newInstance(Class, int) 2548 * @jvms 6.5 {@code anewarray} Instruction 2549 * @since 9 2550 */ 2551 public static 2552 MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 2553 if (!arrayClass.isArray()) { 2554 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 2555 } 2556 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 2557 bindTo(arrayClass.getComponentType()); 2558 return ani.asType(ani.type().changeReturnType(arrayClass)); 2559 } 2560 2561 /** 2562 * Produces a method handle returning the length of an array, 2563 * as if by the {@code arraylength} bytecode. 2564 * The type of the method handle will have {@code int} as return type, 2565 * and its sole argument will be the array type. 2566 * 2567 * <p> If the returned method handle is invoked with a {@code null} 2568 * array reference, a {@code NullPointerException} will be thrown. 2569 * 2570 * @param arrayClass an array type 2571 * @return a method handle which can retrieve the length of an array of the given array type 2572 * @throws NullPointerException if the argument is {@code null} 2573 * @throws IllegalArgumentException if arrayClass is not an array type 2574 * @jvms 6.5 {@code arraylength} Instruction 2575 * @since 9 2576 */ 2577 public static 2578 MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 2579 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 2580 } 2581 2582 /** 2583 * Produces a method handle giving read access to elements of an array, 2584 * as if by the {@code aaload} bytecode. 2585 * The type of the method handle will have a return type of the array's 2586 * element type. Its first argument will be the array type, 2587 * and the second will be {@code int}. 2588 * 2589 * <p> When the returned method handle is invoked, 2590 * the array reference and array index are checked. 2591 * A {@code NullPointerException} will be thrown if the array reference 2592 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 2593 * thrown if the index is negative or if it is greater than or equal to 2594 * the length of the array. 2595 * 2596 * @param arrayClass an array type 2597 * @return a method handle which can load values from the given array type 2598 * @throws NullPointerException if the argument is null 2599 * @throws IllegalArgumentException if arrayClass is not an array type 2600 * @jvms 6.5 {@code aaload} Instruction 2601 */ 2602 public static 2603 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 2604 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 2605 } 2606 2607 /** 2608 * Produces a method handle giving write access to elements of an array, 2609 * as if by the {@code astore} bytecode. 2610 * The type of the method handle will have a void return type. 2611 * Its last argument will be the array's element type. 2612 * The first and second arguments will be the array type and int. 2613 * 2614 * <p> When the returned method handle is invoked, 2615 * the array reference and array index are checked. 2616 * A {@code NullPointerException} will be thrown if the array reference 2617 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 2618 * thrown if the index is negative or if it is greater than or equal to 2619 * the length of the array. 2620 * 2621 * @param arrayClass the class of an array 2622 * @return a method handle which can store values into the array type 2623 * @throws NullPointerException if the argument is null 2624 * @throws IllegalArgumentException if arrayClass is not an array type 2625 * @jvms 6.5 {@code aastore} Instruction 2626 */ 2627 public static 2628 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 2629 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 2630 } 2631 2632 /** 2633 * Produces a VarHandle giving access to elements of an array of type 2634 * {@code arrayClass}. The VarHandle's variable type is the component type 2635 * of {@code arrayClass} and the list of coordinate types is 2636 * {@code (arrayClass, int)}, where the {@code int} coordinate type 2637 * corresponds to an argument that is an index into an array. 2638 * <p> 2639 * Certain access modes of the returned VarHandle are unsupported under 2640 * the following conditions: 2641 * <ul> 2642 * <li>if the component type is anything other than {@code byte}, 2643 * {@code short}, {@code char}, {@code int}, {@code long}, 2644 * {@code float}, or {@code double} then numeric atomic update access 2645 * modes are unsupported. 2646 * <li>if the field type is anything other than {@code boolean}, 2647 * {@code byte}, {@code short}, {@code char}, {@code int} or 2648 * {@code long} then bitwise atomic update access modes are 2649 * unsupported. 2650 * </ul> 2651 * <p> 2652 * If the component type is {@code float} or {@code double} then numeric 2653 * and atomic update access modes compare values using their bitwise 2654 * representation (see {@link Float#floatToRawIntBits} and 2655 * {@link Double#doubleToRawLongBits}, respectively). 2656 * 2657 * <p> When the returned {@code VarHandle} is invoked, 2658 * the array reference and array index are checked. 2659 * A {@code NullPointerException} will be thrown if the array reference 2660 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 2661 * thrown if the index is negative or if it is greater than or equal to 2662 * the length of the array. 2663 * 2664 * @apiNote 2665 * Bitwise comparison of {@code float} values or {@code double} values, 2666 * as performed by the numeric and atomic update access modes, differ 2667 * from the primitive {@code ==} operator and the {@link Float#equals} 2668 * and {@link Double#equals} methods, specifically with respect to 2669 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 2670 * Care should be taken when performing a compare and set or a compare 2671 * and exchange operation with such values since the operation may 2672 * unexpectedly fail. 2673 * There are many possible NaN values that are considered to be 2674 * {@code NaN} in Java, although no IEEE 754 floating-point operation 2675 * provided by Java can distinguish between them. Operation failure can 2676 * occur if the expected or witness value is a NaN value and it is 2677 * transformed (perhaps in a platform specific manner) into another NaN 2678 * value, and thus has a different bitwise representation (see 2679 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 2680 * details). 2681 * The values {@code -0.0} and {@code +0.0} have different bitwise 2682 * representations but are considered equal when using the primitive 2683 * {@code ==} operator. Operation failure can occur if, for example, a 2684 * numeric algorithm computes an expected value to be say {@code -0.0} 2685 * and previously computed the witness value to be say {@code +0.0}. 2686 * @param arrayClass the class of an array, of type {@code T[]} 2687 * @return a VarHandle giving access to elements of an array 2688 * @throws NullPointerException if the arrayClass is null 2689 * @throws IllegalArgumentException if arrayClass is not an array type 2690 * @since 9 2691 */ 2692 public static 2693 VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 2694 return VarHandles.makeArrayElementHandle(arrayClass); 2695 } 2696 2697 /** 2698 * Produces a VarHandle giving access to elements of a {@code byte[]} array 2699 * viewed as if it were a different primitive array type, such as 2700 * {@code int[]} or {@code long[]}. 2701 * The VarHandle's variable type is the component type of 2702 * {@code viewArrayClass} and the list of coordinate types is 2703 * {@code (byte[], int)}, where the {@code int} coordinate type 2704 * corresponds to an argument that is an index into a {@code byte[]} array. 2705 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 2706 * array, composing bytes to or from a value of the component type of 2707 * {@code viewArrayClass} according to the given endianness. 2708 * <p> 2709 * The supported component types (variables types) are {@code short}, 2710 * {@code char}, {@code int}, {@code long}, {@code float} and 2711 * {@code double}. 2712 * <p> 2713 * Access of bytes at a given index will result in an 2714 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2715 * or greater than the {@code byte[]} array length minus the size (in bytes) 2716 * of {@code T}. 2717 * <p> 2718 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2719 * with respect to the underlying memory address, {@code A} say, associated 2720 * with the array and index. 2721 * If access is misaligned then access for anything other than the 2722 * {@code get} and {@code set} access modes will result in an 2723 * {@code IllegalStateException}. In such cases atomic access is only 2724 * guaranteed with respect to the largest power of two that divides the GCD 2725 * of {@code A} and the size (in bytes) of {@code T}. 2726 * If access is aligned then following access modes are supported and are 2727 * guaranteed to support atomic access: 2728 * <ul> 2729 * <li>read write access modes for all {@code T}, with the exception of 2730 * access modes {@code get} and {@code set} for {@code long} and 2731 * {@code double} on 32-bit platforms. 2732 * <li>atomic update access modes for {@code int}, {@code long}, 2733 * {@code float} or {@code double}. 2734 * (Future major platform releases of the JDK may support additional 2735 * types for certain currently unsupported access modes.) 2736 * <li>numeric 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 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 2740 * (Future major platform releases of the JDK may support additional 2741 * numeric types for certain currently unsupported access modes.) 2742 * </ul> 2743 * <p> 2744 * Misaligned access, and therefore atomicity guarantees, may be determined 2745 * for {@code byte[]} arrays without operating on a specific array. Given 2746 * an {@code index}, {@code T} and it's corresponding boxed type, 2747 * {@code T_BOX}, misalignment may be determined as follows: 2748 * <pre>{@code 2749 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2750 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 2751 * alignmentOffset(0, sizeOfT); 2752 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 2753 * boolean isMisaligned = misalignedAtIndex != 0; 2754 * }</pre> 2755 * <p> 2756 * If the variable type is {@code float} or {@code double} then atomic 2757 * update access modes compare values using their bitwise representation 2758 * (see {@link Float#floatToRawIntBits} and 2759 * {@link Double#doubleToRawLongBits}, respectively). 2760 * @param viewArrayClass the view array class, with a component type of 2761 * type {@code T} 2762 * @param byteOrder the endianness of the view array elements, as 2763 * stored in the underlying {@code byte} array 2764 * @return a VarHandle giving access to elements of a {@code byte[]} array 2765 * viewed as if elements corresponding to the components type of the view 2766 * array class 2767 * @throws NullPointerException if viewArrayClass or byteOrder is null 2768 * @throws IllegalArgumentException if viewArrayClass is not an array type 2769 * @throws UnsupportedOperationException if the component type of 2770 * viewArrayClass is not supported as a variable type 2771 * @since 9 2772 */ 2773 public static 2774 VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 2775 ByteOrder byteOrder) throws IllegalArgumentException { 2776 Objects.requireNonNull(byteOrder); 2777 return VarHandles.byteArrayViewHandle(viewArrayClass, 2778 byteOrder == ByteOrder.BIG_ENDIAN); 2779 } 2780 2781 /** 2782 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 2783 * viewed as if it were an array of elements of a different primitive 2784 * component type to that of {@code byte}, such as {@code int[]} or 2785 * {@code long[]}. 2786 * The VarHandle's variable type is the component type of 2787 * {@code viewArrayClass} and the list of coordinate types is 2788 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 2789 * corresponds to an argument that is an index into a {@code byte[]} array. 2790 * The returned VarHandle accesses bytes at an index in a 2791 * {@code ByteBuffer}, composing bytes to or from a value of the component 2792 * type of {@code viewArrayClass} according to the given endianness. 2793 * <p> 2794 * The supported component types (variables types) are {@code short}, 2795 * {@code char}, {@code int}, {@code long}, {@code float} and 2796 * {@code double}. 2797 * <p> 2798 * Access will result in a {@code ReadOnlyBufferException} for anything 2799 * other than the read access modes if the {@code ByteBuffer} is read-only. 2800 * <p> 2801 * Access of bytes at a given index will result in an 2802 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2803 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 2804 * {@code T}. 2805 * <p> 2806 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2807 * with respect to the underlying memory address, {@code A} say, associated 2808 * with the {@code ByteBuffer} and index. 2809 * If access is misaligned then access for anything other than the 2810 * {@code get} and {@code set} access modes will result in an 2811 * {@code IllegalStateException}. In such cases atomic access is only 2812 * guaranteed with respect to the largest power of two that divides the GCD 2813 * of {@code A} and the size (in bytes) of {@code T}. 2814 * If access is aligned then following access modes are supported and are 2815 * guaranteed to support atomic access: 2816 * <ul> 2817 * <li>read write access modes for all {@code T}, with the exception of 2818 * access modes {@code get} and {@code set} for {@code long} and 2819 * {@code double} on 32-bit platforms. 2820 * <li>atomic update access modes for {@code int}, {@code long}, 2821 * {@code float} or {@code double}. 2822 * (Future major platform releases of the JDK may support additional 2823 * types for certain currently unsupported access modes.) 2824 * <li>numeric 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 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 2828 * (Future major platform releases of the JDK may support additional 2829 * numeric types for certain currently unsupported access modes.) 2830 * </ul> 2831 * <p> 2832 * Misaligned access, and therefore atomicity guarantees, may be determined 2833 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 2834 * {@code index}, {@code T} and it's corresponding boxed type, 2835 * {@code T_BOX}, as follows: 2836 * <pre>{@code 2837 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2838 * ByteBuffer bb = ... 2839 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 2840 * boolean isMisaligned = misalignedAtIndex != 0; 2841 * }</pre> 2842 * <p> 2843 * If the variable type is {@code float} or {@code double} then atomic 2844 * update access modes compare values using their bitwise representation 2845 * (see {@link Float#floatToRawIntBits} and 2846 * {@link Double#doubleToRawLongBits}, respectively). 2847 * @param viewArrayClass the view array class, with a component type of 2848 * type {@code T} 2849 * @param byteOrder the endianness of the view array elements, as 2850 * stored in the underlying {@code ByteBuffer} (Note this overrides the 2851 * endianness of a {@code ByteBuffer}) 2852 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 2853 * viewed as if elements corresponding to the components type of the view 2854 * array class 2855 * @throws NullPointerException if viewArrayClass or byteOrder is null 2856 * @throws IllegalArgumentException if viewArrayClass is not an array type 2857 * @throws UnsupportedOperationException if the component type of 2858 * viewArrayClass is not supported as a variable type 2859 * @since 9 2860 */ 2861 public static 2862 VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 2863 ByteOrder byteOrder) throws IllegalArgumentException { 2864 Objects.requireNonNull(byteOrder); 2865 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 2866 byteOrder == ByteOrder.BIG_ENDIAN); 2867 } 2868 2869 2870 /// method handle invocation (reflective style) 2871 2872 /** 2873 * Produces a method handle which will invoke any method handle of the 2874 * given {@code type}, with a given number of trailing arguments replaced by 2875 * a single trailing {@code Object[]} array. 2876 * The resulting invoker will be a method handle with the following 2877 * arguments: 2878 * <ul> 2879 * <li>a single {@code MethodHandle} target 2880 * <li>zero or more leading values (counted by {@code leadingArgCount}) 2881 * <li>an {@code Object[]} array containing trailing arguments 2882 * </ul> 2883 * <p> 2884 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 2885 * the indicated {@code type}. 2886 * That is, if the target is exactly of the given {@code type}, it will behave 2887 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 2888 * is used to convert the target to the required {@code type}. 2889 * <p> 2890 * The type of the returned invoker will not be the given {@code type}, but rather 2891 * will have all parameters except the first {@code leadingArgCount} 2892 * replaced by a single array of type {@code Object[]}, which will be 2893 * the final parameter. 2894 * <p> 2895 * Before invoking its target, the invoker will spread the final array, apply 2896 * reference casts as necessary, and unbox and widen primitive arguments. 2897 * If, when the invoker is called, the supplied array argument does 2898 * not have the correct number of elements, the invoker will throw 2899 * an {@link IllegalArgumentException} instead of invoking the target. 2900 * <p> 2901 * This method is equivalent to the following code (though it may be more efficient): 2902 * <blockquote><pre>{@code 2903 MethodHandle invoker = MethodHandles.invoker(type); 2904 int spreadArgCount = type.parameterCount() - leadingArgCount; 2905 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 2906 return invoker; 2907 * }</pre></blockquote> 2908 * This method throws no reflective or security exceptions. 2909 * @param type the desired target type 2910 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 2911 * @return a method handle suitable for invoking any method handle of the given type 2912 * @throws NullPointerException if {@code type} is null 2913 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 2914 * the range from 0 to {@code type.parameterCount()} inclusive, 2915 * or if the resulting method handle's type would have 2916 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2917 */ 2918 public static 2919 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 2920 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 2921 throw newIllegalArgumentException("bad argument count", leadingArgCount); 2922 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 2923 return type.invokers().spreadInvoker(leadingArgCount); 2924 } 2925 2926 /** 2927 * Produces a special <em>invoker method handle</em> which can be used to 2928 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 2929 * The resulting invoker will have a type which is 2930 * exactly equal to the desired type, except that it will accept 2931 * an additional leading argument of type {@code MethodHandle}. 2932 * <p> 2933 * This method is equivalent to the following code (though it may be more efficient): 2934 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 2935 * 2936 * <p style="font-size:smaller;"> 2937 * <em>Discussion:</em> 2938 * Invoker method handles can be useful when working with variable method handles 2939 * of unknown types. 2940 * For example, to emulate an {@code invokeExact} call to a variable method 2941 * handle {@code M}, extract its type {@code T}, 2942 * look up the invoker method {@code X} for {@code T}, 2943 * and call the invoker method, as {@code X.invoke(T, A...)}. 2944 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 2945 * is unknown.) 2946 * If spreading, collecting, or other argument transformations are required, 2947 * they can be applied once to the invoker {@code X} and reused on many {@code M} 2948 * method handle values, as long as they are compatible with the type of {@code X}. 2949 * <p style="font-size:smaller;"> 2950 * <em>(Note: The invoker method is not available via the Core Reflection API. 2951 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2952 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2953 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2954 * <p> 2955 * This method throws no reflective or security exceptions. 2956 * @param type the desired target type 2957 * @return a method handle suitable for invoking any method handle of the given type 2958 * @throws IllegalArgumentException if the resulting method handle's type would have 2959 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2960 */ 2961 public static 2962 MethodHandle exactInvoker(MethodType type) { 2963 return type.invokers().exactInvoker(); 2964 } 2965 2966 /** 2967 * Produces a special <em>invoker method handle</em> which can be used to 2968 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 2969 * The resulting invoker will have a type which is 2970 * exactly equal to the desired type, except that it will accept 2971 * an additional leading argument of type {@code MethodHandle}. 2972 * <p> 2973 * Before invoking its target, if the target differs from the expected type, 2974 * the invoker will apply reference casts as 2975 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 2976 * Similarly, the return value will be converted as necessary. 2977 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 2978 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 2979 * <p> 2980 * This method is equivalent to the following code (though it may be more efficient): 2981 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 2982 * <p style="font-size:smaller;"> 2983 * <em>Discussion:</em> 2984 * A {@linkplain MethodType#genericMethodType general method type} is one which 2985 * mentions only {@code Object} arguments and return values. 2986 * An invoker for such a type is capable of calling any method handle 2987 * of the same arity as the general type. 2988 * <p style="font-size:smaller;"> 2989 * <em>(Note: The invoker method is not available via the Core Reflection API. 2990 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2991 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2992 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2993 * <p> 2994 * This method throws no reflective or security exceptions. 2995 * @param type the desired target type 2996 * @return a method handle suitable for invoking any method handle convertible to the given type 2997 * @throws IllegalArgumentException if the resulting method handle's type would have 2998 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2999 */ 3000 public static 3001 MethodHandle invoker(MethodType type) { 3002 return type.invokers().genericInvoker(); 3003 } 3004 3005 /** 3006 * Produces a special <em>invoker method handle</em> which can be used to 3007 * invoke a signature-polymorphic access mode method on any VarHandle whose 3008 * associated access mode type is compatible with the given type. 3009 * The resulting invoker will have a type which is exactly equal to the 3010 * desired given type, except that it will accept an additional leading 3011 * argument of type {@code VarHandle}. 3012 * 3013 * @param accessMode the VarHandle access mode 3014 * @param type the desired target type 3015 * @return a method handle suitable for invoking an access mode method of 3016 * any VarHandle whose access mode type is of the given type. 3017 * @since 9 3018 */ 3019 static public 3020 MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 3021 return type.invokers().varHandleMethodExactInvoker(accessMode); 3022 } 3023 3024 /** 3025 * Produces a special <em>invoker method handle</em> which can be used to 3026 * invoke a signature-polymorphic access mode method on any VarHandle whose 3027 * associated access mode type is compatible with the given type. 3028 * The resulting invoker will have a type which is exactly equal to the 3029 * desired given type, except that it will accept an additional leading 3030 * argument of type {@code VarHandle}. 3031 * <p> 3032 * Before invoking its target, if the access mode type differs from the 3033 * desired given type, the invoker will apply reference casts as necessary 3034 * and box, unbox, or widen primitive values, as if by 3035 * {@link MethodHandle#asType asType}. Similarly, the return value will be 3036 * converted as necessary. 3037 * <p> 3038 * This method is equivalent to the following code (though it may be more 3039 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 3040 * 3041 * @param accessMode the VarHandle access mode 3042 * @param type the desired target type 3043 * @return a method handle suitable for invoking an access mode method of 3044 * any VarHandle whose access mode type is convertible to the given 3045 * type. 3046 * @since 9 3047 */ 3048 static public 3049 MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 3050 return type.invokers().varHandleMethodInvoker(accessMode); 3051 } 3052 3053 static /*non-public*/ 3054 MethodHandle basicInvoker(MethodType type) { 3055 return type.invokers().basicInvoker(); 3056 } 3057 3058 /// method handle modification (creation from other method handles) 3059 3060 /** 3061 * Produces a method handle which adapts the type of the 3062 * given method handle to a new type by pairwise argument and return type conversion. 3063 * The original type and new type must have the same number of arguments. 3064 * The resulting method handle is guaranteed to report a type 3065 * which is equal to the desired new type. 3066 * <p> 3067 * If the original type and new type are equal, returns target. 3068 * <p> 3069 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 3070 * and some additional conversions are also applied if those conversions fail. 3071 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 3072 * if possible, before or instead of any conversions done by {@code asType}: 3073 * <ul> 3074 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 3075 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 3076 * (This treatment of interfaces follows the usage of the bytecode verifier.) 3077 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 3078 * the boolean is converted to a byte value, 1 for true, 0 for false. 3079 * (This treatment follows the usage of the bytecode verifier.) 3080 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 3081 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 3082 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 3083 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 3084 * then a Java casting conversion (JLS 5.5) is applied. 3085 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 3086 * widening and/or narrowing.) 3087 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 3088 * conversion will be applied at runtime, possibly followed 3089 * by a Java casting conversion (JLS 5.5) on the primitive value, 3090 * possibly followed by a conversion from byte to boolean by testing 3091 * the low-order bit. 3092 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 3093 * and if the reference is null at runtime, a zero value is introduced. 3094 * </ul> 3095 * @param target the method handle to invoke after arguments are retyped 3096 * @param newType the expected type of the new method handle 3097 * @return a method handle which delegates to the target after performing 3098 * any necessary argument conversions, and arranges for any 3099 * necessary return value conversions 3100 * @throws NullPointerException if either argument is null 3101 * @throws WrongMethodTypeException if the conversion cannot be made 3102 * @see MethodHandle#asType 3103 */ 3104 public static 3105 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 3106 explicitCastArgumentsChecks(target, newType); 3107 // use the asTypeCache when possible: 3108 MethodType oldType = target.type(); 3109 if (oldType == newType) return target; 3110 if (oldType.explicitCastEquivalentToAsType(newType)) { 3111 return target.asFixedArity().asType(newType); 3112 } 3113 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 3114 } 3115 3116 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 3117 if (target.type().parameterCount() != newType.parameterCount()) { 3118 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 3119 } 3120 } 3121 3122 /** 3123 * Produces a method handle which adapts the calling sequence of the 3124 * given method handle to a new type, by reordering the arguments. 3125 * The resulting method handle is guaranteed to report a type 3126 * which is equal to the desired new type. 3127 * <p> 3128 * The given array controls the reordering. 3129 * Call {@code #I} the number of incoming parameters (the value 3130 * {@code newType.parameterCount()}, and call {@code #O} the number 3131 * of outgoing parameters (the value {@code target.type().parameterCount()}). 3132 * Then the length of the reordering array must be {@code #O}, 3133 * and each element must be a non-negative number less than {@code #I}. 3134 * For every {@code N} less than {@code #O}, the {@code N}-th 3135 * outgoing argument will be taken from the {@code I}-th incoming 3136 * argument, where {@code I} is {@code reorder[N]}. 3137 * <p> 3138 * No argument or return value conversions are applied. 3139 * The type of each incoming argument, as determined by {@code newType}, 3140 * must be identical to the type of the corresponding outgoing parameter 3141 * or parameters in the target method handle. 3142 * The return type of {@code newType} must be identical to the return 3143 * type of the original target. 3144 * <p> 3145 * The reordering array need not specify an actual permutation. 3146 * An incoming argument will be duplicated if its index appears 3147 * more than once in the array, and an incoming argument will be dropped 3148 * if its index does not appear in the array. 3149 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 3150 * incoming arguments which are not mentioned in the reordering array 3151 * may be of any type, as determined only by {@code newType}. 3152 * <blockquote><pre>{@code 3153 import static java.lang.invoke.MethodHandles.*; 3154 import static java.lang.invoke.MethodType.*; 3155 ... 3156 MethodType intfn1 = methodType(int.class, int.class); 3157 MethodType intfn2 = methodType(int.class, int.class, int.class); 3158 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 3159 assert(sub.type().equals(intfn2)); 3160 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 3161 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 3162 assert((int)rsub.invokeExact(1, 100) == 99); 3163 MethodHandle add = ... (int x, int y) -> (x+y) ...; 3164 assert(add.type().equals(intfn2)); 3165 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 3166 assert(twice.type().equals(intfn1)); 3167 assert((int)twice.invokeExact(21) == 42); 3168 * }</pre></blockquote> 3169 * <p> 3170 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3171 * variable-arity method handle}, even if the original target method handle was. 3172 * @param target the method handle to invoke after arguments are reordered 3173 * @param newType the expected type of the new method handle 3174 * @param reorder an index array which controls the reordering 3175 * @return a method handle which delegates to the target after it 3176 * drops unused arguments and moves and/or duplicates the other arguments 3177 * @throws NullPointerException if any argument is null 3178 * @throws IllegalArgumentException if the index array length is not equal to 3179 * the arity of the target, or if any index array element 3180 * not a valid index for a parameter of {@code newType}, 3181 * or if two corresponding parameter types in 3182 * {@code target.type()} and {@code newType} are not identical, 3183 */ 3184 public static 3185 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 3186 reorder = reorder.clone(); // get a private copy 3187 MethodType oldType = target.type(); 3188 permuteArgumentChecks(reorder, newType, oldType); 3189 // first detect dropped arguments and handle them separately 3190 int[] originalReorder = reorder; 3191 BoundMethodHandle result = target.rebind(); 3192 LambdaForm form = result.form; 3193 int newArity = newType.parameterCount(); 3194 // Normalize the reordering into a real permutation, 3195 // by removing duplicates and adding dropped elements. 3196 // This somewhat improves lambda form caching, as well 3197 // as simplifying the transform by breaking it up into steps. 3198 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 3199 if (ddIdx > 0) { 3200 // We found a duplicated entry at reorder[ddIdx]. 3201 // Example: (x,y,z)->asList(x,y,z) 3202 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 3203 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 3204 // The starred element corresponds to the argument 3205 // deleted by the dupArgumentForm transform. 3206 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 3207 boolean killFirst = false; 3208 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 3209 // Set killFirst if the dup is larger than an intervening position. 3210 // This will remove at least one inversion from the permutation. 3211 if (dupVal > val) killFirst = true; 3212 } 3213 if (!killFirst) { 3214 srcPos = dstPos; 3215 dstPos = ddIdx; 3216 } 3217 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 3218 assert (reorder[srcPos] == reorder[dstPos]); 3219 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 3220 // contract the reordering by removing the element at dstPos 3221 int tailPos = dstPos + 1; 3222 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 3223 reorder = Arrays.copyOf(reorder, reorder.length - 1); 3224 } else { 3225 int dropVal = ~ddIdx, insPos = 0; 3226 while (insPos < reorder.length && reorder[insPos] < dropVal) { 3227 // Find first element of reorder larger than dropVal. 3228 // This is where we will insert the dropVal. 3229 insPos += 1; 3230 } 3231 Class<?> ptype = newType.parameterType(dropVal); 3232 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 3233 oldType = oldType.insertParameterTypes(insPos, ptype); 3234 // expand the reordering by inserting an element at insPos 3235 int tailPos = insPos + 1; 3236 reorder = Arrays.copyOf(reorder, reorder.length + 1); 3237 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 3238 reorder[insPos] = dropVal; 3239 } 3240 assert (permuteArgumentChecks(reorder, newType, oldType)); 3241 } 3242 assert (reorder.length == newArity); // a perfect permutation 3243 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 3244 form = form.editor().permuteArgumentsForm(1, reorder); 3245 if (newType == result.type() && form == result.internalForm()) 3246 return result; 3247 return result.copyWith(newType, form); 3248 } 3249 3250 /** 3251 * Return an indication of any duplicate or omission in reorder. 3252 * If the reorder contains a duplicate entry, return the index of the second occurrence. 3253 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 3254 * Otherwise, return zero. 3255 * If an element not in [0..newArity-1] is encountered, return reorder.length. 3256 */ 3257 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 3258 final int BIT_LIMIT = 63; // max number of bits in bit mask 3259 if (newArity < BIT_LIMIT) { 3260 long mask = 0; 3261 for (int i = 0; i < reorder.length; i++) { 3262 int arg = reorder[i]; 3263 if (arg >= newArity) { 3264 return reorder.length; 3265 } 3266 long bit = 1L << arg; 3267 if ((mask & bit) != 0) { 3268 return i; // >0 indicates a dup 3269 } 3270 mask |= bit; 3271 } 3272 if (mask == (1L << newArity) - 1) { 3273 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 3274 return 0; 3275 } 3276 // find first zero 3277 long zeroBit = Long.lowestOneBit(~mask); 3278 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 3279 assert(zeroPos <= newArity); 3280 if (zeroPos == newArity) { 3281 return 0; 3282 } 3283 return ~zeroPos; 3284 } else { 3285 // same algorithm, different bit set 3286 BitSet mask = new BitSet(newArity); 3287 for (int i = 0; i < reorder.length; i++) { 3288 int arg = reorder[i]; 3289 if (arg >= newArity) { 3290 return reorder.length; 3291 } 3292 if (mask.get(arg)) { 3293 return i; // >0 indicates a dup 3294 } 3295 mask.set(arg); 3296 } 3297 int zeroPos = mask.nextClearBit(0); 3298 assert(zeroPos <= newArity); 3299 if (zeroPos == newArity) { 3300 return 0; 3301 } 3302 return ~zeroPos; 3303 } 3304 } 3305 3306 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 3307 if (newType.returnType() != oldType.returnType()) 3308 throw newIllegalArgumentException("return types do not match", 3309 oldType, newType); 3310 if (reorder.length == oldType.parameterCount()) { 3311 int limit = newType.parameterCount(); 3312 boolean bad = false; 3313 for (int j = 0; j < reorder.length; j++) { 3314 int i = reorder[j]; 3315 if (i < 0 || i >= limit) { 3316 bad = true; break; 3317 } 3318 Class<?> src = newType.parameterType(i); 3319 Class<?> dst = oldType.parameterType(j); 3320 if (src != dst) 3321 throw newIllegalArgumentException("parameter types do not match after reorder", 3322 oldType, newType); 3323 } 3324 if (!bad) return true; 3325 } 3326 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 3327 } 3328 3329 /** 3330 * Produces a method handle of the requested return type which returns the given 3331 * constant value every time it is invoked. 3332 * <p> 3333 * Before the method handle is returned, the passed-in value is converted to the requested type. 3334 * If the requested type is primitive, widening primitive conversions are attempted, 3335 * else reference conversions are attempted. 3336 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 3337 * @param type the return type of the desired method handle 3338 * @param value the value to return 3339 * @return a method handle of the given return type and no arguments, which always returns the given value 3340 * @throws NullPointerException if the {@code type} argument is null 3341 * @throws ClassCastException if the value cannot be converted to the required return type 3342 * @throws IllegalArgumentException if the given type is {@code void.class} 3343 */ 3344 public static 3345 MethodHandle constant(Class<?> type, Object value) { 3346 if (type.isPrimitive()) { 3347 if (type == void.class) 3348 throw newIllegalArgumentException("void type"); 3349 Wrapper w = Wrapper.forPrimitiveType(type); 3350 value = w.convert(value, type); 3351 if (w.zero().equals(value)) 3352 return zero(w, type); 3353 return insertArguments(identity(type), 0, value); 3354 } else { 3355 if (value == null) 3356 return zero(Wrapper.OBJECT, type); 3357 return identity(type).bindTo(value); 3358 } 3359 } 3360 3361 /** 3362 * Produces a method handle which returns its sole argument when invoked. 3363 * @param type the type of the sole parameter and return value of the desired method handle 3364 * @return a unary method handle which accepts and returns the given type 3365 * @throws NullPointerException if the argument is null 3366 * @throws IllegalArgumentException if the given type is {@code void.class} 3367 */ 3368 public static 3369 MethodHandle identity(Class<?> type) { 3370 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 3371 int pos = btw.ordinal(); 3372 MethodHandle ident = IDENTITY_MHS[pos]; 3373 if (ident == null) { 3374 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 3375 } 3376 if (ident.type().returnType() == type) 3377 return ident; 3378 // something like identity(Foo.class); do not bother to intern these 3379 assert (btw == Wrapper.OBJECT); 3380 return makeIdentity(type); 3381 } 3382 3383 /** 3384 * Produces a constant method handle of the requested return type which 3385 * returns the default value for that type every time it is invoked. 3386 * The resulting constant method handle will have no side effects. 3387 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 3388 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 3389 * since {@code explicitCastArguments} converts {@code null} to default values. 3390 * @param type the expected return type of the desired method handle 3391 * @return a constant method handle that takes no arguments 3392 * and returns the default value of the given type (or void, if the type is void) 3393 * @throws NullPointerException if the argument is null 3394 * @see MethodHandles#constant 3395 * @see MethodHandles#empty 3396 * @see MethodHandles#explicitCastArguments 3397 * @since 9 3398 */ 3399 public static MethodHandle zero(Class<?> type) { 3400 Objects.requireNonNull(type); 3401 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 3402 } 3403 3404 private static MethodHandle identityOrVoid(Class<?> type) { 3405 return type == void.class ? zero(type) : identity(type); 3406 } 3407 3408 /** 3409 * Produces a method handle of the requested type which ignores any arguments, does nothing, 3410 * and returns a suitable default depending on the return type. 3411 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 3412 * <p>The returned method handle is equivalent to 3413 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 3414 * 3415 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 3416 * {@code guardWithTest(pred, target, empty(target.type())}. 3417 * @param type the type of the desired method handle 3418 * @return a constant method handle of the given type, which returns a default value of the given return type 3419 * @throws NullPointerException if the argument is null 3420 * @see MethodHandles#zero 3421 * @see MethodHandles#constant 3422 * @since 9 3423 */ 3424 public static MethodHandle empty(MethodType type) { 3425 Objects.requireNonNull(type); 3426 return dropArguments(zero(type.returnType()), 0, type.parameterList()); 3427 } 3428 3429 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 3430 private static MethodHandle makeIdentity(Class<?> ptype) { 3431 MethodType mtype = methodType(ptype, ptype); 3432 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 3433 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 3434 } 3435 3436 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 3437 int pos = btw.ordinal(); 3438 MethodHandle zero = ZERO_MHS[pos]; 3439 if (zero == null) { 3440 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 3441 } 3442 if (zero.type().returnType() == rtype) 3443 return zero; 3444 assert(btw == Wrapper.OBJECT); 3445 return makeZero(rtype); 3446 } 3447 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 3448 private static MethodHandle makeZero(Class<?> rtype) { 3449 MethodType mtype = methodType(rtype); 3450 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 3451 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 3452 } 3453 3454 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 3455 // Simulate a CAS, to avoid racy duplication of results. 3456 MethodHandle prev = cache[pos]; 3457 if (prev != null) return prev; 3458 return cache[pos] = value; 3459 } 3460 3461 /** 3462 * Provides a target method handle with one or more <em>bound arguments</em> 3463 * in advance of the method handle's invocation. 3464 * The formal parameters to the target corresponding to the bound 3465 * arguments are called <em>bound parameters</em>. 3466 * Returns a new method handle which saves away the bound arguments. 3467 * When it is invoked, it receives arguments for any non-bound parameters, 3468 * binds the saved arguments to their corresponding parameters, 3469 * and calls the original target. 3470 * <p> 3471 * The type of the new method handle will drop the types for the bound 3472 * parameters from the original target type, since the new method handle 3473 * will no longer require those arguments to be supplied by its callers. 3474 * <p> 3475 * Each given argument object must match the corresponding bound parameter type. 3476 * If a bound parameter type is a primitive, the argument object 3477 * must be a wrapper, and will be unboxed to produce the primitive value. 3478 * <p> 3479 * The {@code pos} argument selects which parameters are to be bound. 3480 * It may range between zero and <i>N-L</i> (inclusively), 3481 * where <i>N</i> is the arity of the target method handle 3482 * and <i>L</i> is the length of the values array. 3483 * <p> 3484 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3485 * variable-arity method handle}, even if the original target method handle was. 3486 * @param target the method handle to invoke after the argument is inserted 3487 * @param pos where to insert the argument (zero for the first) 3488 * @param values the series of arguments to insert 3489 * @return a method handle which inserts an additional argument, 3490 * before calling the original method handle 3491 * @throws NullPointerException if the target or the {@code values} array is null 3492 * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than 3493 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 3494 * is the length of the values array. 3495 * @throws ClassCastException if an argument does not match the corresponding bound parameter 3496 * type. 3497 * @see MethodHandle#bindTo 3498 */ 3499 public static 3500 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 3501 int insCount = values.length; 3502 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 3503 if (insCount == 0) return target; 3504 BoundMethodHandle result = target.rebind(); 3505 for (int i = 0; i < insCount; i++) { 3506 Object value = values[i]; 3507 Class<?> ptype = ptypes[pos+i]; 3508 if (ptype.isPrimitive()) { 3509 result = insertArgumentPrimitive(result, pos, ptype, value); 3510 } else { 3511 value = ptype.cast(value); // throw CCE if needed 3512 result = result.bindArgumentL(pos, value); 3513 } 3514 } 3515 return result; 3516 } 3517 3518 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 3519 Class<?> ptype, Object value) { 3520 Wrapper w = Wrapper.forPrimitiveType(ptype); 3521 // perform unboxing and/or primitive conversion 3522 value = w.convert(value, ptype); 3523 switch (w) { 3524 case INT: return result.bindArgumentI(pos, (int)value); 3525 case LONG: return result.bindArgumentJ(pos, (long)value); 3526 case FLOAT: return result.bindArgumentF(pos, (float)value); 3527 case DOUBLE: return result.bindArgumentD(pos, (double)value); 3528 default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 3529 } 3530 } 3531 3532 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 3533 MethodType oldType = target.type(); 3534 int outargs = oldType.parameterCount(); 3535 int inargs = outargs - insCount; 3536 if (inargs < 0) 3537 throw newIllegalArgumentException("too many values to insert"); 3538 if (pos < 0 || pos > inargs) 3539 throw newIllegalArgumentException("no argument type to append"); 3540 return oldType.ptypes(); 3541 } 3542 3543 /** 3544 * Produces a method handle which will discard some dummy arguments 3545 * before calling some other specified <i>target</i> method handle. 3546 * The type of the new method handle will be the same as the target's type, 3547 * except it will also include the dummy argument types, 3548 * at some given position. 3549 * <p> 3550 * The {@code pos} argument may range between zero and <i>N</i>, 3551 * where <i>N</i> is the arity of the target. 3552 * If {@code pos} is zero, the dummy arguments will precede 3553 * the target's real arguments; if {@code pos} is <i>N</i> 3554 * they will come after. 3555 * <p> 3556 * <b>Example:</b> 3557 * <blockquote><pre>{@code 3558 import static java.lang.invoke.MethodHandles.*; 3559 import static java.lang.invoke.MethodType.*; 3560 ... 3561 MethodHandle cat = lookup().findVirtual(String.class, 3562 "concat", methodType(String.class, String.class)); 3563 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3564 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 3565 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 3566 assertEquals(bigType, d0.type()); 3567 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 3568 * }</pre></blockquote> 3569 * <p> 3570 * This method is also equivalent to the following code: 3571 * <blockquote><pre> 3572 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 3573 * </pre></blockquote> 3574 * @param target the method handle to invoke after the arguments are dropped 3575 * @param valueTypes the type(s) of the argument(s) to drop 3576 * @param pos position of first argument to drop (zero for the leftmost) 3577 * @return a method handle which drops arguments of the given types, 3578 * before calling the original method handle 3579 * @throws NullPointerException if the target is null, 3580 * or if the {@code valueTypes} list or any of its elements is null 3581 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3582 * or if {@code pos} is negative or greater than the arity of the target, 3583 * or if the new method handle's type would have too many parameters 3584 */ 3585 public static 3586 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3587 return dropArguments0(target, pos, copyTypes(valueTypes.toArray())); 3588 } 3589 3590 private static List<Class<?>> copyTypes(Object[] array) { 3591 return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class)); 3592 } 3593 3594 private static 3595 MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3596 MethodType oldType = target.type(); // get NPE 3597 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 3598 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 3599 if (dropped == 0) return target; 3600 BoundMethodHandle result = target.rebind(); 3601 LambdaForm lform = result.form; 3602 int insertFormArg = 1 + pos; 3603 for (Class<?> ptype : valueTypes) { 3604 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 3605 } 3606 result = result.copyWith(newType, lform); 3607 return result; 3608 } 3609 3610 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { 3611 int dropped = valueTypes.size(); 3612 MethodType.checkSlotCount(dropped); 3613 int outargs = oldType.parameterCount(); 3614 int inargs = outargs + dropped; 3615 if (pos < 0 || pos > outargs) 3616 throw newIllegalArgumentException("no argument type to remove" 3617 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 3618 ); 3619 return dropped; 3620 } 3621 3622 /** 3623 * Produces a method handle which will discard some dummy arguments 3624 * before calling some other specified <i>target</i> method handle. 3625 * The type of the new method handle will be the same as the target's type, 3626 * except it will also include the dummy argument types, 3627 * at some given position. 3628 * <p> 3629 * The {@code pos} argument may range between zero and <i>N</i>, 3630 * where <i>N</i> is the arity of the target. 3631 * If {@code pos} is zero, the dummy arguments will precede 3632 * the target's real arguments; if {@code pos} is <i>N</i> 3633 * they will come after. 3634 * @apiNote 3635 * <blockquote><pre>{@code 3636 import static java.lang.invoke.MethodHandles.*; 3637 import static java.lang.invoke.MethodType.*; 3638 ... 3639 MethodHandle cat = lookup().findVirtual(String.class, 3640 "concat", methodType(String.class, String.class)); 3641 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3642 MethodHandle d0 = dropArguments(cat, 0, String.class); 3643 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 3644 MethodHandle d1 = dropArguments(cat, 1, String.class); 3645 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 3646 MethodHandle d2 = dropArguments(cat, 2, String.class); 3647 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 3648 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 3649 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 3650 * }</pre></blockquote> 3651 * <p> 3652 * This method is also equivalent to the following code: 3653 * <blockquote><pre> 3654 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 3655 * </pre></blockquote> 3656 * @param target the method handle to invoke after the arguments are dropped 3657 * @param valueTypes the type(s) of the argument(s) to drop 3658 * @param pos position of first argument to drop (zero for the leftmost) 3659 * @return a method handle which drops arguments of the given types, 3660 * before calling the original method handle 3661 * @throws NullPointerException if the target is null, 3662 * or if the {@code valueTypes} array or any of its elements is null 3663 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3664 * or if {@code pos} is negative or greater than the arity of the target, 3665 * or if the new method handle's type would have 3666 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3667 */ 3668 public static 3669 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 3670 return dropArguments0(target, pos, copyTypes(valueTypes)); 3671 } 3672 3673 // private version which allows caller some freedom with error handling 3674 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, 3675 boolean nullOnFailure) { 3676 newTypes = copyTypes(newTypes.toArray()); 3677 List<Class<?>> oldTypes = target.type().parameterList(); 3678 int match = oldTypes.size(); 3679 if (skip != 0) { 3680 if (skip < 0 || skip > match) { 3681 throw newIllegalArgumentException("illegal skip", skip, target); 3682 } 3683 oldTypes = oldTypes.subList(skip, match); 3684 match -= skip; 3685 } 3686 List<Class<?>> addTypes = newTypes; 3687 int add = addTypes.size(); 3688 if (pos != 0) { 3689 if (pos < 0 || pos > add) { 3690 throw newIllegalArgumentException("illegal pos", pos, newTypes); 3691 } 3692 addTypes = addTypes.subList(pos, add); 3693 add -= pos; 3694 assert(addTypes.size() == add); 3695 } 3696 // Do not add types which already match the existing arguments. 3697 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { 3698 if (nullOnFailure) { 3699 return null; 3700 } 3701 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); 3702 } 3703 addTypes = addTypes.subList(match, add); 3704 add -= match; 3705 assert(addTypes.size() == add); 3706 // newTypes: ( P*[pos], M*[match], A*[add] ) 3707 // target: ( S*[skip], M*[match] ) 3708 MethodHandle adapter = target; 3709 if (add > 0) { 3710 adapter = dropArguments0(adapter, skip+ match, addTypes); 3711 } 3712 // adapter: (S*[skip], M*[match], A*[add] ) 3713 if (pos > 0) { 3714 adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos)); 3715 } 3716 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 3717 return adapter; 3718 } 3719 3720 /** 3721 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 3722 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 3723 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 3724 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 3725 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 3726 * {@link #dropArguments(MethodHandle, int, Class[])}. 3727 * <p> 3728 * The resulting handle will have the same return type as the target handle. 3729 * <p> 3730 * In more formal terms, assume these two type lists:<ul> 3731 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 3732 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 3733 * {@code newTypes}. 3734 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 3735 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 3736 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 3737 * sub-list. 3738 * </ul> 3739 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 3740 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 3741 * {@link #dropArguments(MethodHandle, int, Class[])}. 3742 * 3743 * @apiNote 3744 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 3745 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 3746 * <blockquote><pre>{@code 3747 import static java.lang.invoke.MethodHandles.*; 3748 import static java.lang.invoke.MethodType.*; 3749 ... 3750 ... 3751 MethodHandle h0 = constant(boolean.class, true); 3752 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 3753 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 3754 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 3755 if (h1.type().parameterCount() < h2.type().parameterCount()) 3756 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 3757 else 3758 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 3759 MethodHandle h3 = guardWithTest(h0, h1, h2); 3760 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 3761 * }</pre></blockquote> 3762 * @param target the method handle to adapt 3763 * @param skip number of targets parameters to disregard (they will be unchanged) 3764 * @param newTypes the list of types to match {@code target}'s parameter type list to 3765 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 3766 * @return a possibly adapted method handle 3767 * @throws NullPointerException if either argument is null 3768 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 3769 * or if {@code skip} is negative or greater than the arity of the target, 3770 * or if {@code pos} is negative or greater than the newTypes list size, 3771 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 3772 * {@code pos}. 3773 * @since 9 3774 */ 3775 public static 3776 MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 3777 Objects.requireNonNull(target); 3778 Objects.requireNonNull(newTypes); 3779 return dropArgumentsToMatch(target, skip, newTypes, pos, false); 3780 } 3781 3782 /** 3783 * Adapts a target method handle by pre-processing 3784 * one or more of its arguments, each with its own unary filter function, 3785 * and then calling the target with each pre-processed argument 3786 * replaced by the result of its corresponding filter function. 3787 * <p> 3788 * The pre-processing is performed by one or more method handles, 3789 * specified in the elements of the {@code filters} array. 3790 * The first element of the filter array corresponds to the {@code pos} 3791 * argument of the target, and so on in sequence. 3792 * The filter functions are invoked in left to right order. 3793 * <p> 3794 * Null arguments in the array are treated as identity functions, 3795 * and the corresponding arguments left unchanged. 3796 * (If there are no non-null elements in the array, the original target is returned.) 3797 * Each filter is applied to the corresponding argument of the adapter. 3798 * <p> 3799 * If a filter {@code F} applies to the {@code N}th argument of 3800 * the target, then {@code F} must be a method handle which 3801 * takes exactly one argument. The type of {@code F}'s sole argument 3802 * replaces the corresponding argument type of the target 3803 * in the resulting adapted method handle. 3804 * The return type of {@code F} must be identical to the corresponding 3805 * parameter type of the target. 3806 * <p> 3807 * It is an error if there are elements of {@code filters} 3808 * (null or not) 3809 * which do not correspond to argument positions in the target. 3810 * <p><b>Example:</b> 3811 * <blockquote><pre>{@code 3812 import static java.lang.invoke.MethodHandles.*; 3813 import static java.lang.invoke.MethodType.*; 3814 ... 3815 MethodHandle cat = lookup().findVirtual(String.class, 3816 "concat", methodType(String.class, String.class)); 3817 MethodHandle upcase = lookup().findVirtual(String.class, 3818 "toUpperCase", methodType(String.class)); 3819 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3820 MethodHandle f0 = filterArguments(cat, 0, upcase); 3821 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 3822 MethodHandle f1 = filterArguments(cat, 1, upcase); 3823 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 3824 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 3825 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 3826 * }</pre></blockquote> 3827 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3828 * denotes the return type of both the {@code target} and resulting adapter. 3829 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 3830 * of the parameters and arguments that precede and follow the filter position 3831 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 3832 * values of the filtered parameters and arguments; they also represent the 3833 * return types of the {@code filter[i]} handles. The latter accept arguments 3834 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 3835 * the resulting adapter. 3836 * <blockquote><pre>{@code 3837 * T target(P... p, A[i]... a[i], B... b); 3838 * A[i] filter[i](V[i]); 3839 * T adapter(P... p, V[i]... v[i], B... b) { 3840 * return target(p..., filter[i](v[i])..., b...); 3841 * } 3842 * }</pre></blockquote> 3843 * <p> 3844 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3845 * variable-arity method handle}, even if the original target method handle was. 3846 * 3847 * @param target the method handle to invoke after arguments are filtered 3848 * @param pos the position of the first argument to filter 3849 * @param filters method handles to call initially on filtered arguments 3850 * @return method handle which incorporates the specified argument filtering logic 3851 * @throws NullPointerException if the target is null 3852 * or if the {@code filters} array is null 3853 * @throws IllegalArgumentException if a non-null element of {@code filters} 3854 * does not match a corresponding argument type of target as described above, 3855 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 3856 * or if the resulting method handle's type would have 3857 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3858 */ 3859 public static 3860 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 3861 filterArgumentsCheckArity(target, pos, filters); 3862 MethodHandle adapter = target; 3863 // process filters in reverse order so that the invocation of 3864 // the resulting adapter will invoke the filters in left-to-right order 3865 for (int i = filters.length - 1; i >= 0; --i) { 3866 MethodHandle filter = filters[i]; 3867 if (filter == null) continue; // ignore null elements of filters 3868 adapter = filterArgument(adapter, pos + i, filter); 3869 } 3870 return adapter; 3871 } 3872 3873 /*non-public*/ static 3874 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 3875 filterArgumentChecks(target, pos, filter); 3876 MethodType targetType = target.type(); 3877 MethodType filterType = filter.type(); 3878 BoundMethodHandle result = target.rebind(); 3879 Class<?> newParamType = filterType.parameterType(0); 3880 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 3881 MethodType newType = targetType.changeParameterType(pos, newParamType); 3882 result = result.copyWithExtendL(newType, lform, filter); 3883 return result; 3884 } 3885 3886 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 3887 MethodType targetType = target.type(); 3888 int maxPos = targetType.parameterCount(); 3889 if (pos + filters.length > maxPos) 3890 throw newIllegalArgumentException("too many filters"); 3891 } 3892 3893 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3894 MethodType targetType = target.type(); 3895 MethodType filterType = filter.type(); 3896 if (filterType.parameterCount() != 1 3897 || filterType.returnType() != targetType.parameterType(pos)) 3898 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3899 } 3900 3901 /** 3902 * Adapts a target method handle by pre-processing 3903 * a sub-sequence of its arguments with a filter (another method handle). 3904 * The pre-processed arguments are replaced by the result (if any) of the 3905 * filter function. 3906 * The target is then called on the modified (usually shortened) argument list. 3907 * <p> 3908 * If the filter returns a value, the target must accept that value as 3909 * its argument in position {@code pos}, preceded and/or followed by 3910 * any arguments not passed to the filter. 3911 * If the filter returns void, the target must accept all arguments 3912 * not passed to the filter. 3913 * No arguments are reordered, and a result returned from the filter 3914 * replaces (in order) the whole subsequence of arguments originally 3915 * passed to the adapter. 3916 * <p> 3917 * The argument types (if any) of the filter 3918 * replace zero or one argument types of the target, at position {@code pos}, 3919 * in the resulting adapted method handle. 3920 * The return type of the filter (if any) must be identical to the 3921 * argument type of the target at position {@code pos}, and that target argument 3922 * is supplied by the return value of the filter. 3923 * <p> 3924 * In all cases, {@code pos} must be greater than or equal to zero, and 3925 * {@code pos} must also be less than or equal to the target's arity. 3926 * <p><b>Example:</b> 3927 * <blockquote><pre>{@code 3928 import static java.lang.invoke.MethodHandles.*; 3929 import static java.lang.invoke.MethodType.*; 3930 ... 3931 MethodHandle deepToString = publicLookup() 3932 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 3933 3934 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 3935 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 3936 3937 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 3938 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 3939 3940 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 3941 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 3942 assertEquals("[top, [up, down], strange]", 3943 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 3944 3945 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 3946 assertEquals("[top, [up, down], [strange]]", 3947 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 3948 3949 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 3950 assertEquals("[top, [[up, down, strange], charm], bottom]", 3951 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 3952 * }</pre></blockquote> 3953 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3954 * represents the return type of the {@code target} and resulting adapter. 3955 * {@code V}/{@code v} stand for the return type and value of the 3956 * {@code filter}, which are also found in the signature and arguments of 3957 * the {@code target}, respectively, unless {@code V} is {@code void}. 3958 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 3959 * and values preceding and following the collection position, {@code pos}, 3960 * in the {@code target}'s signature. They also turn up in the resulting 3961 * adapter's signature and arguments, where they surround 3962 * {@code B}/{@code b}, which represent the parameter types and arguments 3963 * to the {@code filter} (if any). 3964 * <blockquote><pre>{@code 3965 * T target(A...,V,C...); 3966 * V filter(B...); 3967 * T adapter(A... a,B... b,C... c) { 3968 * V v = filter(b...); 3969 * return target(a...,v,c...); 3970 * } 3971 * // and if the filter has no arguments: 3972 * T target2(A...,V,C...); 3973 * V filter2(); 3974 * T adapter2(A... a,C... c) { 3975 * V v = filter2(); 3976 * return target2(a...,v,c...); 3977 * } 3978 * // and if the filter has a void return: 3979 * T target3(A...,C...); 3980 * void filter3(B...); 3981 * T adapter3(A... a,B... b,C... c) { 3982 * filter3(b...); 3983 * return target3(a...,c...); 3984 * } 3985 * }</pre></blockquote> 3986 * <p> 3987 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 3988 * one which first "folds" the affected arguments, and then drops them, in separate 3989 * steps as follows: 3990 * <blockquote><pre>{@code 3991 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 3992 * mh = MethodHandles.foldArguments(mh, coll); //step 1 3993 * }</pre></blockquote> 3994 * If the target method handle consumes no arguments besides than the result 3995 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 3996 * is equivalent to {@code filterReturnValue(coll, mh)}. 3997 * If the filter method handle {@code coll} consumes one argument and produces 3998 * a non-void result, then {@code collectArguments(mh, N, coll)} 3999 * is equivalent to {@code filterArguments(mh, N, coll)}. 4000 * Other equivalences are possible but would require argument permutation. 4001 * <p> 4002 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4003 * variable-arity method handle}, even if the original target method handle was. 4004 * 4005 * @param target the method handle to invoke after filtering the subsequence of arguments 4006 * @param pos the position of the first adapter argument to pass to the filter, 4007 * and/or the target argument which receives the result of the filter 4008 * @param filter method handle to call on the subsequence of arguments 4009 * @return method handle which incorporates the specified argument subsequence filtering logic 4010 * @throws NullPointerException if either argument is null 4011 * @throws IllegalArgumentException if the return type of {@code filter} 4012 * is non-void and is not the same as the {@code pos} argument of the target, 4013 * or if {@code pos} is not between 0 and the target's arity, inclusive, 4014 * or if the resulting method handle's type would have 4015 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4016 * @see MethodHandles#foldArguments 4017 * @see MethodHandles#filterArguments 4018 * @see MethodHandles#filterReturnValue 4019 */ 4020 public static 4021 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 4022 MethodType newType = collectArgumentsChecks(target, pos, filter); 4023 MethodType collectorType = filter.type(); 4024 BoundMethodHandle result = target.rebind(); 4025 LambdaForm lform; 4026 if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { 4027 lform = result.editor().collectArgumentArrayForm(1 + pos, filter); 4028 if (lform != null) { 4029 return result.copyWith(newType, lform); 4030 } 4031 } 4032 lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 4033 return result.copyWithExtendL(newType, lform, filter); 4034 } 4035 4036 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 4037 MethodType targetType = target.type(); 4038 MethodType filterType = filter.type(); 4039 Class<?> rtype = filterType.returnType(); 4040 List<Class<?>> filterArgs = filterType.parameterList(); 4041 if (rtype == void.class) { 4042 return targetType.insertParameterTypes(pos, filterArgs); 4043 } 4044 if (rtype != targetType.parameterType(pos)) { 4045 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 4046 } 4047 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); 4048 } 4049 4050 /** 4051 * Adapts a target method handle by post-processing 4052 * its return value (if any) with a filter (another method handle). 4053 * The result of the filter is returned from the adapter. 4054 * <p> 4055 * If the target returns a value, the filter must accept that value as 4056 * its only argument. 4057 * If the target returns void, the filter must accept no arguments. 4058 * <p> 4059 * The return type of the filter 4060 * replaces the return type of the target 4061 * in the resulting adapted method handle. 4062 * The argument type of the filter (if any) must be identical to the 4063 * return type of the target. 4064 * <p><b>Example:</b> 4065 * <blockquote><pre>{@code 4066 import static java.lang.invoke.MethodHandles.*; 4067 import static java.lang.invoke.MethodType.*; 4068 ... 4069 MethodHandle cat = lookup().findVirtual(String.class, 4070 "concat", methodType(String.class, String.class)); 4071 MethodHandle length = lookup().findVirtual(String.class, 4072 "length", methodType(int.class)); 4073 System.out.println((String) cat.invokeExact("x", "y")); // xy 4074 MethodHandle f0 = filterReturnValue(cat, length); 4075 System.out.println((int) f0.invokeExact("x", "y")); // 2 4076 * }</pre></blockquote> 4077 * <p>Here is pseudocode for the resulting adapter. In the code, 4078 * {@code T}/{@code t} represent the result type and value of the 4079 * {@code target}; {@code V}, the result type of the {@code filter}; and 4080 * {@code A}/{@code a}, the types and values of the parameters and arguments 4081 * of the {@code target} as well as the resulting adapter. 4082 * <blockquote><pre>{@code 4083 * T target(A...); 4084 * V filter(T); 4085 * V adapter(A... a) { 4086 * T t = target(a...); 4087 * return filter(t); 4088 * } 4089 * // and if the target has a void return: 4090 * void target2(A...); 4091 * V filter2(); 4092 * V adapter2(A... a) { 4093 * target2(a...); 4094 * return filter2(); 4095 * } 4096 * // and if the filter has a void return: 4097 * T target3(A...); 4098 * void filter3(V); 4099 * void adapter3(A... a) { 4100 * T t = target3(a...); 4101 * filter3(t); 4102 * } 4103 * }</pre></blockquote> 4104 * <p> 4105 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4106 * variable-arity method handle}, even if the original target method handle was. 4107 * @param target the method handle to invoke before filtering the return value 4108 * @param filter method handle to call on the return value 4109 * @return method handle which incorporates the specified return value filtering logic 4110 * @throws NullPointerException if either argument is null 4111 * @throws IllegalArgumentException if the argument list of {@code filter} 4112 * does not match the return type of target as described above 4113 */ 4114 public static 4115 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 4116 MethodType targetType = target.type(); 4117 MethodType filterType = filter.type(); 4118 filterReturnValueChecks(targetType, filterType); 4119 BoundMethodHandle result = target.rebind(); 4120 BasicType rtype = BasicType.basicType(filterType.returnType()); 4121 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 4122 MethodType newType = targetType.changeReturnType(filterType.returnType()); 4123 result = result.copyWithExtendL(newType, lform, filter); 4124 return result; 4125 } 4126 4127 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 4128 Class<?> rtype = targetType.returnType(); 4129 int filterValues = filterType.parameterCount(); 4130 if (filterValues == 0 4131 ? (rtype != void.class) 4132 : (rtype != filterType.parameterType(0) || filterValues != 1)) 4133 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 4134 } 4135 4136 /** 4137 * Adapts a target method handle by pre-processing 4138 * some of its arguments, and then calling the target with 4139 * the result of the pre-processing, inserted into the original 4140 * sequence of arguments. 4141 * <p> 4142 * The pre-processing is performed by {@code combiner}, a second method handle. 4143 * Of the arguments passed to the adapter, the first {@code N} arguments 4144 * are copied to the combiner, which is then called. 4145 * (Here, {@code N} is defined as the parameter count of the combiner.) 4146 * After this, control passes to the target, with any result 4147 * from the combiner inserted before the original {@code N} incoming 4148 * arguments. 4149 * <p> 4150 * If the combiner returns a value, the first parameter type of the target 4151 * must be identical with the return type of the combiner, and the next 4152 * {@code N} parameter types of the target must exactly match the parameters 4153 * of the combiner. 4154 * <p> 4155 * If the combiner has a void return, no result will be inserted, 4156 * and the first {@code N} parameter types of the target 4157 * must exactly match the parameters of the combiner. 4158 * <p> 4159 * The resulting adapter is the same type as the target, except that the 4160 * first parameter type is dropped, 4161 * if it corresponds to the result of the combiner. 4162 * <p> 4163 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 4164 * that either the combiner or the target does not wish to receive. 4165 * If some of the incoming arguments are destined only for the combiner, 4166 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 4167 * arguments will not need to be live on the stack on entry to the 4168 * target.) 4169 * <p><b>Example:</b> 4170 * <blockquote><pre>{@code 4171 import static java.lang.invoke.MethodHandles.*; 4172 import static java.lang.invoke.MethodType.*; 4173 ... 4174 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 4175 "println", methodType(void.class, String.class)) 4176 .bindTo(System.out); 4177 MethodHandle cat = lookup().findVirtual(String.class, 4178 "concat", methodType(String.class, String.class)); 4179 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 4180 MethodHandle catTrace = foldArguments(cat, trace); 4181 // also prints "boo": 4182 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 4183 * }</pre></blockquote> 4184 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 4185 * represents the result type of the {@code target} and resulting adapter. 4186 * {@code V}/{@code v} represent the type and value of the parameter and argument 4187 * of {@code target} that precedes the folding position; {@code V} also is 4188 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 4189 * types and values of the {@code N} parameters and arguments at the folding 4190 * position. {@code B}/{@code b} represent the types and values of the 4191 * {@code target} parameters and arguments that follow the folded parameters 4192 * and arguments. 4193 * <blockquote><pre>{@code 4194 * // there are N arguments in A... 4195 * T target(V, A[N]..., B...); 4196 * V combiner(A...); 4197 * T adapter(A... a, B... b) { 4198 * V v = combiner(a...); 4199 * return target(v, a..., b...); 4200 * } 4201 * // and if the combiner has a void return: 4202 * T target2(A[N]..., B...); 4203 * void combiner2(A...); 4204 * T adapter2(A... a, B... b) { 4205 * combiner2(a...); 4206 * return target2(a..., b...); 4207 * } 4208 * }</pre></blockquote> 4209 * <p> 4210 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4211 * variable-arity method handle}, even if the original target method handle was. 4212 * @param target the method handle to invoke after arguments are combined 4213 * @param combiner method handle to call initially on the incoming arguments 4214 * @return method handle which incorporates the specified argument folding logic 4215 * @throws NullPointerException if either argument is null 4216 * @throws IllegalArgumentException if {@code combiner}'s return type 4217 * is non-void and not the same as the first argument type of 4218 * the target, or if the initial {@code N} argument types 4219 * of the target 4220 * (skipping one matching the {@code combiner}'s return type) 4221 * are not identical with the argument types of {@code combiner} 4222 */ 4223 public static 4224 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 4225 return foldArguments(target, 0, combiner); 4226 } 4227 4228 /** 4229 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 4230 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 4231 * before the folded arguments. 4232 * <p> 4233 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 4234 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 4235 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 4236 * 0. 4237 * 4238 * @apiNote Example: 4239 * <blockquote><pre>{@code 4240 import static java.lang.invoke.MethodHandles.*; 4241 import static java.lang.invoke.MethodType.*; 4242 ... 4243 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 4244 "println", methodType(void.class, String.class)) 4245 .bindTo(System.out); 4246 MethodHandle cat = lookup().findVirtual(String.class, 4247 "concat", methodType(String.class, String.class)); 4248 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 4249 MethodHandle catTrace = foldArguments(cat, 1, trace); 4250 // also prints "jum": 4251 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 4252 * }</pre></blockquote> 4253 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 4254 * represents the result type of the {@code target} and resulting adapter. 4255 * {@code V}/{@code v} represent the type and value of the parameter and argument 4256 * of {@code target} that precedes the folding position; {@code V} also is 4257 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 4258 * types and values of the {@code N} parameters and arguments at the folding 4259 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 4260 * and values of the {@code target} parameters and arguments that precede and 4261 * follow the folded parameters and arguments starting at {@code pos}, 4262 * respectively. 4263 * <blockquote><pre>{@code 4264 * // there are N arguments in A... 4265 * T target(Z..., V, A[N]..., B...); 4266 * V combiner(A...); 4267 * T adapter(Z... z, A... a, B... b) { 4268 * V v = combiner(a...); 4269 * return target(z..., v, a..., b...); 4270 * } 4271 * // and if the combiner has a void return: 4272 * T target2(Z..., A[N]..., B...); 4273 * void combiner2(A...); 4274 * T adapter2(Z... z, A... a, B... b) { 4275 * combiner2(a...); 4276 * return target2(z..., a..., b...); 4277 * } 4278 * }</pre></blockquote> 4279 * <p> 4280 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4281 * variable-arity method handle}, even if the original target method handle was. 4282 * 4283 * @param target the method handle to invoke after arguments are combined 4284 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 4285 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 4286 * @param combiner method handle to call initially on the incoming arguments 4287 * @return method handle which incorporates the specified argument folding logic 4288 * @throws NullPointerException if either argument is null 4289 * @throws IllegalArgumentException if either of the following two conditions holds: 4290 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 4291 * {@code pos} of the target signature; 4292 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 4293 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 4294 * 4295 * @see #foldArguments(MethodHandle, MethodHandle) 4296 * @since 9 4297 */ 4298 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 4299 MethodType targetType = target.type(); 4300 MethodType combinerType = combiner.type(); 4301 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 4302 BoundMethodHandle result = target.rebind(); 4303 boolean dropResult = rtype == void.class; 4304 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 4305 MethodType newType = targetType; 4306 if (!dropResult) { 4307 newType = newType.dropParameterTypes(pos, pos + 1); 4308 } 4309 result = result.copyWithExtendL(newType, lform, combiner); 4310 return result; 4311 } 4312 4313 /** 4314 * As {@see foldArguments(MethodHandle, int, MethodHandle)}, but with the 4315 * added capability of selecting the arguments from the targets parameters 4316 * to call the combiner with. This allows us to avoid some simple cases of 4317 * permutations and padding the combiner with dropArguments to select the 4318 * right argument, which may ultimately produce fewer intermediaries. 4319 */ 4320 static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner, int ... argPositions) { 4321 MethodType targetType = target.type(); 4322 MethodType combinerType = combiner.type(); 4323 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType, argPositions); 4324 BoundMethodHandle result = target.rebind(); 4325 boolean dropResult = rtype == void.class; 4326 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType(), argPositions); 4327 MethodType newType = targetType; 4328 if (!dropResult) { 4329 newType = newType.dropParameterTypes(pos, pos + 1); 4330 } 4331 result = result.copyWithExtendL(newType, lform, combiner); 4332 return result; 4333 } 4334 4335 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 4336 int foldArgs = combinerType.parameterCount(); 4337 Class<?> rtype = combinerType.returnType(); 4338 int foldVals = rtype == void.class ? 0 : 1; 4339 int afterInsertPos = foldPos + foldVals; 4340 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 4341 if (ok) { 4342 for (int i = 0; i < foldArgs; i++) { 4343 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 4344 ok = false; 4345 break; 4346 } 4347 } 4348 } 4349 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 4350 ok = false; 4351 if (!ok) 4352 throw misMatchedTypes("target and combiner types", targetType, combinerType); 4353 return rtype; 4354 } 4355 4356 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType, int ... argPos) { 4357 int foldArgs = combinerType.parameterCount(); 4358 if (argPos.length != foldArgs) { 4359 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 4360 } 4361 Class<?> rtype = combinerType.returnType(); 4362 int foldVals = rtype == void.class ? 0 : 1; 4363 boolean ok = true; 4364 for (int i = 0; i < foldArgs; i++) { 4365 int arg = argPos[i]; 4366 if (arg < 0 || arg > targetType.parameterCount()) { 4367 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 4368 } 4369 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 4370 throw newIllegalArgumentException("target argument type at position " + arg 4371 + " must match combiner argument type at index " + i + ": " + targetType 4372 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 4373 } 4374 } 4375 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) { 4376 ok = false; 4377 } 4378 if (!ok) 4379 throw misMatchedTypes("target and combiner types", targetType, combinerType); 4380 return rtype; 4381 } 4382 4383 /** 4384 * Makes a method handle which adapts a target method handle, 4385 * by guarding it with a test, a boolean-valued method handle. 4386 * If the guard fails, a fallback handle is called instead. 4387 * All three method handles must have the same corresponding 4388 * argument and return types, except that the return type 4389 * of the test must be boolean, and the test is allowed 4390 * to have fewer arguments than the other two method handles. 4391 * <p> 4392 * Here is pseudocode for the resulting adapter. In the code, {@code T} 4393 * represents the uniform result type of the three involved handles; 4394 * {@code A}/{@code a}, the types and values of the {@code target} 4395 * parameters and arguments that are consumed by the {@code test}; and 4396 * {@code B}/{@code b}, those types and values of the {@code target} 4397 * parameters and arguments that are not consumed by the {@code test}. 4398 * <blockquote><pre>{@code 4399 * boolean test(A...); 4400 * T target(A...,B...); 4401 * T fallback(A...,B...); 4402 * T adapter(A... a,B... b) { 4403 * if (test(a...)) 4404 * return target(a..., b...); 4405 * else 4406 * return fallback(a..., b...); 4407 * } 4408 * }</pre></blockquote> 4409 * Note that the test arguments ({@code a...} in the pseudocode) cannot 4410 * be modified by execution of the test, and so are passed unchanged 4411 * from the caller to the target or fallback as appropriate. 4412 * @param test method handle used for test, must return boolean 4413 * @param target method handle to call if test passes 4414 * @param fallback method handle to call if test fails 4415 * @return method handle which incorporates the specified if/then/else logic 4416 * @throws NullPointerException if any argument is null 4417 * @throws IllegalArgumentException if {@code test} does not return boolean, 4418 * or if all three method types do not match (with the return 4419 * type of {@code test} changed to match that of the target). 4420 */ 4421 public static 4422 MethodHandle guardWithTest(MethodHandle test, 4423 MethodHandle target, 4424 MethodHandle fallback) { 4425 MethodType gtype = test.type(); 4426 MethodType ttype = target.type(); 4427 MethodType ftype = fallback.type(); 4428 if (!ttype.equals(ftype)) 4429 throw misMatchedTypes("target and fallback types", ttype, ftype); 4430 if (gtype.returnType() != boolean.class) 4431 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 4432 List<Class<?>> targs = ttype.parameterList(); 4433 test = dropArgumentsToMatch(test, 0, targs, 0, true); 4434 if (test == null) { 4435 throw misMatchedTypes("target and test types", ttype, gtype); 4436 } 4437 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 4438 } 4439 4440 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 4441 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 4442 } 4443 4444 /** 4445 * Makes a method handle which adapts a target method handle, 4446 * by running it inside an exception handler. 4447 * If the target returns normally, the adapter returns that value. 4448 * If an exception matching the specified type is thrown, the fallback 4449 * handle is called instead on the exception, plus the original arguments. 4450 * <p> 4451 * The target and handler must have the same corresponding 4452 * argument and return types, except that handler may omit trailing arguments 4453 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 4454 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 4455 * <p> 4456 * Here is pseudocode for the resulting adapter. In the code, {@code T} 4457 * represents the return type of the {@code target} and {@code handler}, 4458 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 4459 * the types and values of arguments to the resulting handle consumed by 4460 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 4461 * resulting handle discarded by {@code handler}. 4462 * <blockquote><pre>{@code 4463 * T target(A..., B...); 4464 * T handler(ExType, A...); 4465 * T adapter(A... a, B... b) { 4466 * try { 4467 * return target(a..., b...); 4468 * } catch (ExType ex) { 4469 * return handler(ex, a...); 4470 * } 4471 * } 4472 * }</pre></blockquote> 4473 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 4474 * be modified by execution of the target, and so are passed unchanged 4475 * from the caller to the handler, if the handler is invoked. 4476 * <p> 4477 * The target and handler must return the same type, even if the handler 4478 * always throws. (This might happen, for instance, because the handler 4479 * is simulating a {@code finally} clause). 4480 * To create such a throwing handler, compose the handler creation logic 4481 * with {@link #throwException throwException}, 4482 * in order to create a method handle of the correct return type. 4483 * @param target method handle to call 4484 * @param exType the type of exception which the handler will catch 4485 * @param handler method handle to call if a matching exception is thrown 4486 * @return method handle which incorporates the specified try/catch logic 4487 * @throws NullPointerException if any argument is null 4488 * @throws IllegalArgumentException if {@code handler} does not accept 4489 * the given exception type, or if the method handle types do 4490 * not match in their return types and their 4491 * corresponding parameters 4492 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 4493 */ 4494 public static 4495 MethodHandle catchException(MethodHandle target, 4496 Class<? extends Throwable> exType, 4497 MethodHandle handler) { 4498 MethodType ttype = target.type(); 4499 MethodType htype = handler.type(); 4500 if (!Throwable.class.isAssignableFrom(exType)) 4501 throw new ClassCastException(exType.getName()); 4502 if (htype.parameterCount() < 1 || 4503 !htype.parameterType(0).isAssignableFrom(exType)) 4504 throw newIllegalArgumentException("handler does not accept exception type "+exType); 4505 if (htype.returnType() != ttype.returnType()) 4506 throw misMatchedTypes("target and handler return types", ttype, htype); 4507 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); 4508 if (handler == null) { 4509 throw misMatchedTypes("target and handler types", ttype, htype); 4510 } 4511 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 4512 } 4513 4514 /** 4515 * Produces a method handle which will throw exceptions of the given {@code exType}. 4516 * The method handle will accept a single argument of {@code exType}, 4517 * and immediately throw it as an exception. 4518 * The method type will nominally specify a return of {@code returnType}. 4519 * The return type may be anything convenient: It doesn't matter to the 4520 * method handle's behavior, since it will never return normally. 4521 * @param returnType the return type of the desired method handle 4522 * @param exType the parameter type of the desired method handle 4523 * @return method handle which can throw the given exceptions 4524 * @throws NullPointerException if either argument is null 4525 */ 4526 public static 4527 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 4528 if (!Throwable.class.isAssignableFrom(exType)) 4529 throw new ClassCastException(exType.getName()); 4530 return MethodHandleImpl.throwException(methodType(returnType, exType)); 4531 } 4532 4533 /** 4534 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 4535 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 4536 * delivers the loop's result, which is the return value of the resulting handle. 4537 * <p> 4538 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 4539 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 4540 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 4541 * terms of method handles, each clause will specify up to four independent actions:<ul> 4542 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 4543 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 4544 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 4545 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 4546 * </ul> 4547 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 4548 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 4549 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 4550 * <p> 4551 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 4552 * this case. See below for a detailed description. 4553 * <p> 4554 * <em>Parameters optional everywhere:</em> 4555 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 4556 * As an exception, the init functions cannot take any {@code v} parameters, 4557 * because those values are not yet computed when the init functions are executed. 4558 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 4559 * In fact, any clause function may take no arguments at all. 4560 * <p> 4561 * <em>Loop parameters:</em> 4562 * A clause function may take all the iteration variable values it is entitled to, in which case 4563 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 4564 * with their types and values notated as {@code (A...)} and {@code (a...)}. 4565 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 4566 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 4567 * init function is automatically a loop parameter {@code a}.) 4568 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 4569 * These loop parameters act as loop-invariant values visible across the whole loop. 4570 * <p> 4571 * <em>Parameters visible everywhere:</em> 4572 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 4573 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 4574 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 4575 * Most clause functions will not need all of this information, but they will be formally connected to it 4576 * as if by {@link #dropArguments}. 4577 * <a id="astar"></a> 4578 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 4579 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 4580 * In that notation, the general form of an init function parameter list 4581 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 4582 * <p> 4583 * <em>Checking clause structure:</em> 4584 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 4585 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 4586 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 4587 * met by the inputs to the loop combinator. 4588 * <p> 4589 * <em>Effectively identical sequences:</em> 4590 * <a id="effid"></a> 4591 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 4592 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 4593 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 4594 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 4595 * that longest list. 4596 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 4597 * and the same is true if more sequences of the form {@code (V... A*)} are added. 4598 * <p> 4599 * <em>Step 0: Determine clause structure.</em><ol type="a"> 4600 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 4601 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 4602 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 4603 * four. Padding takes place by appending elements to the array. 4604 * <li>Clauses with all {@code null}s are disregarded. 4605 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 4606 * </ol> 4607 * <p> 4608 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 4609 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 4610 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 4611 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 4612 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 4613 * iteration variable type. 4614 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 4615 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 4616 * </ol> 4617 * <p> 4618 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 4619 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 4620 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 4621 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 4622 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 4623 * (These types will checked in step 2, along with all the clause function types.) 4624 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 4625 * <li>All of the collected parameter lists must be effectively identical. 4626 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 4627 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 4628 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 4629 * the "internal parameter list". 4630 * </ul> 4631 * <p> 4632 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 4633 * <li>Examine fini function return types, disregarding omitted fini functions. 4634 * <li>If there are no fini functions, the loop return type is {@code void}. 4635 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 4636 * type. 4637 * </ol> 4638 * <p> 4639 * <em>Step 1D: Check other types.</em><ol type="a"> 4640 * <li>There must be at least one non-omitted pred function. 4641 * <li>Every non-omitted pred function must have a {@code boolean} return type. 4642 * </ol> 4643 * <p> 4644 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 4645 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 4646 * <li>The parameter list for init functions will be adjusted to the external parameter list. 4647 * (Note that their parameter lists are already effectively identical to this list.) 4648 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 4649 * effectively identical to the internal parameter list {@code (V... A...)}. 4650 * </ol> 4651 * <p> 4652 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 4653 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 4654 * type. 4655 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 4656 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 4657 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 4658 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 4659 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 4660 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 4661 * loop return type. 4662 * </ol> 4663 * <p> 4664 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 4665 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 4666 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 4667 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 4668 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 4669 * pad out the end of the list. 4670 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 4671 * </ol> 4672 * <p> 4673 * <em>Final observations.</em><ol type="a"> 4674 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 4675 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 4676 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 4677 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 4678 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 4679 * <li>Each pair of init and step functions agrees in their return type {@code V}. 4680 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 4681 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 4682 * </ol> 4683 * <p> 4684 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 4685 * <ul> 4686 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 4687 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 4688 * (Only one {@code Pn} has to be non-{@code null}.) 4689 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 4690 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 4691 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 4692 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 4693 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 4694 * the resulting loop handle's parameter types {@code (A...)}. 4695 * </ul> 4696 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 4697 * which is natural if most of the loop computation happens in the steps. For some loops, 4698 * the burden of computation might be heaviest in the pred functions, and so the pred functions 4699 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 4700 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 4701 * where the init functions will need the extra parameters. For such reasons, the rules for 4702 * determining these parameters are as symmetric as possible, across all clause parts. 4703 * In general, the loop parameters function as common invariant values across the whole 4704 * loop, while the iteration variables function as common variant values, or (if there is 4705 * no step function) as internal loop invariant temporaries. 4706 * <p> 4707 * <em>Loop execution.</em><ol type="a"> 4708 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 4709 * every clause function. These locals are loop invariant. 4710 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 4711 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 4712 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 4713 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 4714 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 4715 * (in argument order). 4716 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 4717 * returns {@code false}. 4718 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 4719 * sequence {@code (v...)} of loop variables. 4720 * The updated value is immediately visible to all subsequent function calls. 4721 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 4722 * (of type {@code R}) is returned from the loop as a whole. 4723 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 4724 * except by throwing an exception. 4725 * </ol> 4726 * <p> 4727 * <em>Usage tips.</em> 4728 * <ul> 4729 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 4730 * sometimes a step function only needs to observe the current value of its own variable. 4731 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 4732 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 4733 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 4734 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 4735 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 4736 * <li>If some of the clause functions are virtual methods on an instance, the instance 4737 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 4738 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 4739 * will be the first iteration variable value, and it will be easy to use virtual 4740 * methods as clause parts, since all of them will take a leading instance reference matching that value. 4741 * </ul> 4742 * <p> 4743 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 4744 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 4745 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 4746 * <blockquote><pre>{@code 4747 * V... init...(A...); 4748 * boolean pred...(V..., A...); 4749 * V... step...(V..., A...); 4750 * R fini...(V..., A...); 4751 * R loop(A... a) { 4752 * V... v... = init...(a...); 4753 * for (;;) { 4754 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 4755 * v = s(v..., a...); 4756 * if (!p(v..., a...)) { 4757 * return f(v..., a...); 4758 * } 4759 * } 4760 * } 4761 * } 4762 * }</pre></blockquote> 4763 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 4764 * to their full length, even though individual clause functions may neglect to take them all. 4765 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 4766 * 4767 * @apiNote Example: 4768 * <blockquote><pre>{@code 4769 * // iterative implementation of the factorial function as a loop handle 4770 * static int one(int k) { return 1; } 4771 * static int inc(int i, int acc, int k) { return i + 1; } 4772 * static int mult(int i, int acc, int k) { return i * acc; } 4773 * static boolean pred(int i, int acc, int k) { return i < k; } 4774 * static int fin(int i, int acc, int k) { return acc; } 4775 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4776 * // null initializer for counter, should initialize to 0 4777 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4778 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4779 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4780 * assertEquals(120, loop.invoke(5)); 4781 * }</pre></blockquote> 4782 * The same example, dropping arguments and using combinators: 4783 * <blockquote><pre>{@code 4784 * // simplified implementation of the factorial function as a loop handle 4785 * static int inc(int i) { return i + 1; } // drop acc, k 4786 * static int mult(int i, int acc) { return i * acc; } //drop k 4787 * static boolean cmp(int i, int k) { return i < k; } 4788 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 4789 * // null initializer for counter, should initialize to 0 4790 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 4791 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 4792 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 4793 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4794 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4795 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4796 * assertEquals(720, loop.invoke(6)); 4797 * }</pre></blockquote> 4798 * A similar example, using a helper object to hold a loop parameter: 4799 * <blockquote><pre>{@code 4800 * // instance-based implementation of the factorial function as a loop handle 4801 * static class FacLoop { 4802 * final int k; 4803 * FacLoop(int k) { this.k = k; } 4804 * int inc(int i) { return i + 1; } 4805 * int mult(int i, int acc) { return i * acc; } 4806 * boolean pred(int i) { return i < k; } 4807 * int fin(int i, int acc) { return acc; } 4808 * } 4809 * // assume MH_FacLoop is a handle to the constructor 4810 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4811 * // null initializer for counter, should initialize to 0 4812 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 4813 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 4814 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4815 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4816 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 4817 * assertEquals(5040, loop.invoke(7)); 4818 * }</pre></blockquote> 4819 * 4820 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 4821 * 4822 * @return a method handle embodying the looping behavior as defined by the arguments. 4823 * 4824 * @throws IllegalArgumentException in case any of the constraints described above is violated. 4825 * 4826 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 4827 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 4828 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 4829 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 4830 * @since 9 4831 */ 4832 public static MethodHandle loop(MethodHandle[]... clauses) { 4833 // Step 0: determine clause structure. 4834 loopChecks0(clauses); 4835 4836 List<MethodHandle> init = new ArrayList<>(); 4837 List<MethodHandle> step = new ArrayList<>(); 4838 List<MethodHandle> pred = new ArrayList<>(); 4839 List<MethodHandle> fini = new ArrayList<>(); 4840 4841 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 4842 init.add(clause[0]); // all clauses have at least length 1 4843 step.add(clause.length <= 1 ? null : clause[1]); 4844 pred.add(clause.length <= 2 ? null : clause[2]); 4845 fini.add(clause.length <= 3 ? null : clause[3]); 4846 }); 4847 4848 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 4849 final int nclauses = init.size(); 4850 4851 // Step 1A: determine iteration variables (V...). 4852 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 4853 for (int i = 0; i < nclauses; ++i) { 4854 MethodHandle in = init.get(i); 4855 MethodHandle st = step.get(i); 4856 if (in == null && st == null) { 4857 iterationVariableTypes.add(void.class); 4858 } else if (in != null && st != null) { 4859 loopChecks1a(i, in, st); 4860 iterationVariableTypes.add(in.type().returnType()); 4861 } else { 4862 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 4863 } 4864 } 4865 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). 4866 collect(Collectors.toList()); 4867 4868 // Step 1B: determine loop parameters (A...). 4869 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 4870 loopChecks1b(init, commonSuffix); 4871 4872 // Step 1C: determine loop return type. 4873 // Step 1D: check other types. 4874 // local variable required here; see JDK-8223553 4875 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 4876 .map(MethodType::returnType); 4877 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 4878 loopChecks1cd(pred, fini, loopReturnType); 4879 4880 // Step 2: determine parameter lists. 4881 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 4882 commonParameterSequence.addAll(commonSuffix); 4883 loopChecks2(step, pred, fini, commonParameterSequence); 4884 4885 // Step 3: fill in omitted functions. 4886 for (int i = 0; i < nclauses; ++i) { 4887 Class<?> t = iterationVariableTypes.get(i); 4888 if (init.get(i) == null) { 4889 init.set(i, empty(methodType(t, commonSuffix))); 4890 } 4891 if (step.get(i) == null) { 4892 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 4893 } 4894 if (pred.get(i) == null) { 4895 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence)); 4896 } 4897 if (fini.get(i) == null) { 4898 fini.set(i, empty(methodType(t, commonParameterSequence))); 4899 } 4900 } 4901 4902 // Step 4: fill in missing parameter types. 4903 // Also convert all handles to fixed-arity handles. 4904 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 4905 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 4906 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 4907 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 4908 4909 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 4910 allMatch(pl -> pl.equals(commonSuffix)); 4911 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 4912 allMatch(pl -> pl.equals(commonParameterSequence)); 4913 4914 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 4915 } 4916 4917 private static void loopChecks0(MethodHandle[][] clauses) { 4918 if (clauses == null || clauses.length == 0) { 4919 throw newIllegalArgumentException("null or no clauses passed"); 4920 } 4921 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 4922 throw newIllegalArgumentException("null clauses are not allowed"); 4923 } 4924 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 4925 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 4926 } 4927 } 4928 4929 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 4930 if (in.type().returnType() != st.type().returnType()) { 4931 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 4932 st.type().returnType()); 4933 } 4934 } 4935 4936 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 4937 final List<Class<?>> empty = List.of(); 4938 final List<Class<?>> longest = mhs.filter(Objects::nonNull). 4939 // take only those that can contribute to a common suffix because they are longer than the prefix 4940 map(MethodHandle::type). 4941 filter(t -> t.parameterCount() > skipSize). 4942 map(MethodType::parameterList). 4943 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 4944 return longest.size() == 0 ? empty : longest.subList(skipSize, longest.size()); 4945 } 4946 4947 private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) { 4948 final List<Class<?>> empty = List.of(); 4949 return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 4950 } 4951 4952 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 4953 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 4954 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 4955 return longestParameterList(Arrays.asList(longest1, longest2)); 4956 } 4957 4958 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 4959 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 4960 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 4961 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 4962 " (common suffix: " + commonSuffix + ")"); 4963 } 4964 } 4965 4966 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 4967 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4968 anyMatch(t -> t != loopReturnType)) { 4969 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 4970 loopReturnType + ")"); 4971 } 4972 4973 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { 4974 throw newIllegalArgumentException("no predicate found", pred); 4975 } 4976 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4977 anyMatch(t -> t != boolean.class)) { 4978 throw newIllegalArgumentException("predicates must have boolean return type", pred); 4979 } 4980 } 4981 4982 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 4983 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 4984 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 4985 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 4986 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 4987 } 4988 } 4989 4990 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 4991 return hs.stream().map(h -> { 4992 int pc = h.type().parameterCount(); 4993 int tpsize = targetParams.size(); 4994 return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h; 4995 }).collect(Collectors.toList()); 4996 } 4997 4998 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 4999 return hs.stream().map(MethodHandle::asFixedArity).collect(Collectors.toList()); 5000 } 5001 5002 /** 5003 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 5004 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5005 * <p> 5006 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 5007 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 5008 * evaluates to {@code true}). 5009 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 5010 * <p> 5011 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 5012 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 5013 * and updated with the value returned from its invocation. The result of loop execution will be 5014 * the final value of the additional loop-local variable (if present). 5015 * <p> 5016 * The following rules hold for these argument handles:<ul> 5017 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5018 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 5019 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5020 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 5021 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 5022 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 5023 * It will constrain the parameter lists of the other loop parts. 5024 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 5025 * list {@code (A...)} is called the <em>external parameter list</em>. 5026 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5027 * additional state variable of the loop. 5028 * The body must both accept and return a value of this type {@code V}. 5029 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5030 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5031 * <a href="MethodHandles.html#effid">effectively identical</a> 5032 * to the external parameter list {@code (A...)}. 5033 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5034 * {@linkplain #empty default value}. 5035 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 5036 * Its parameter list (either empty or of the form {@code (V A*)}) must be 5037 * effectively identical to the internal parameter list. 5038 * </ul> 5039 * <p> 5040 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5041 * <li>The loop handle's result type is the result type {@code V} of the body. 5042 * <li>The loop handle's parameter types are the types {@code (A...)}, 5043 * from the external parameter list. 5044 * </ul> 5045 * <p> 5046 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5047 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 5048 * passed to the loop. 5049 * <blockquote><pre>{@code 5050 * V init(A...); 5051 * boolean pred(V, A...); 5052 * V body(V, A...); 5053 * V whileLoop(A... a...) { 5054 * V v = init(a...); 5055 * while (pred(v, a...)) { 5056 * v = body(v, a...); 5057 * } 5058 * return v; 5059 * } 5060 * }</pre></blockquote> 5061 * 5062 * @apiNote Example: 5063 * <blockquote><pre>{@code 5064 * // implement the zip function for lists as a loop handle 5065 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 5066 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 5067 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 5068 * zip.add(a.next()); 5069 * zip.add(b.next()); 5070 * return zip; 5071 * } 5072 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 5073 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 5074 * List<String> a = Arrays.asList("a", "b", "c", "d"); 5075 * List<String> b = Arrays.asList("e", "f", "g", "h"); 5076 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 5077 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 5078 * }</pre></blockquote> 5079 * 5080 * 5081 * @apiNote The implementation of this method can be expressed as follows: 5082 * <blockquote><pre>{@code 5083 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 5084 * MethodHandle fini = (body.type().returnType() == void.class 5085 * ? null : identity(body.type().returnType())); 5086 * MethodHandle[] 5087 * checkExit = { null, null, pred, fini }, 5088 * varBody = { init, body }; 5089 * return loop(checkExit, varBody); 5090 * } 5091 * }</pre></blockquote> 5092 * 5093 * @param init optional initializer, providing the initial value of the loop variable. 5094 * May be {@code null}, implying a default initial value. See above for other constraints. 5095 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 5096 * above for other constraints. 5097 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 5098 * See above for other constraints. 5099 * 5100 * @return a method handle implementing the {@code while} loop as described by the arguments. 5101 * @throws IllegalArgumentException if the rules for the arguments are violated. 5102 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 5103 * 5104 * @see #loop(MethodHandle[][]) 5105 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 5106 * @since 9 5107 */ 5108 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 5109 whileLoopChecks(init, pred, body); 5110 MethodHandle fini = identityOrVoid(body.type().returnType()); 5111 MethodHandle[] checkExit = { null, null, pred, fini }; 5112 MethodHandle[] varBody = { init, body }; 5113 return loop(checkExit, varBody); 5114 } 5115 5116 /** 5117 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 5118 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5119 * <p> 5120 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 5121 * method will, in each iteration, first execute its body and then evaluate the predicate. 5122 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 5123 * <p> 5124 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 5125 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 5126 * and updated with the value returned from its invocation. The result of loop execution will be 5127 * the final value of the additional loop-local variable (if present). 5128 * <p> 5129 * The following rules hold for these argument handles:<ul> 5130 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5131 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 5132 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5133 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 5134 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 5135 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 5136 * It will constrain the parameter lists of the other loop parts. 5137 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 5138 * list {@code (A...)} is called the <em>external parameter list</em>. 5139 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5140 * additional state variable of the loop. 5141 * The body must both accept and return a value of this type {@code V}. 5142 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5143 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5144 * <a href="MethodHandles.html#effid">effectively identical</a> 5145 * to the external parameter list {@code (A...)}. 5146 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5147 * {@linkplain #empty default value}. 5148 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 5149 * Its parameter list (either empty or of the form {@code (V A*)}) must be 5150 * effectively identical to the internal parameter list. 5151 * </ul> 5152 * <p> 5153 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5154 * <li>The loop handle's result type is the result type {@code V} of the body. 5155 * <li>The loop handle's parameter types are the types {@code (A...)}, 5156 * from the external parameter list. 5157 * </ul> 5158 * <p> 5159 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5160 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 5161 * passed to the loop. 5162 * <blockquote><pre>{@code 5163 * V init(A...); 5164 * boolean pred(V, A...); 5165 * V body(V, A...); 5166 * V doWhileLoop(A... a...) { 5167 * V v = init(a...); 5168 * do { 5169 * v = body(v, a...); 5170 * } while (pred(v, a...)); 5171 * return v; 5172 * } 5173 * }</pre></blockquote> 5174 * 5175 * @apiNote Example: 5176 * <blockquote><pre>{@code 5177 * // int i = 0; while (i < limit) { ++i; } return i; => limit 5178 * static int zero(int limit) { return 0; } 5179 * static int step(int i, int limit) { return i + 1; } 5180 * static boolean pred(int i, int limit) { return i < limit; } 5181 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 5182 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 5183 * assertEquals(23, loop.invoke(23)); 5184 * }</pre></blockquote> 5185 * 5186 * 5187 * @apiNote The implementation of this method can be expressed as follows: 5188 * <blockquote><pre>{@code 5189 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 5190 * MethodHandle fini = (body.type().returnType() == void.class 5191 * ? null : identity(body.type().returnType())); 5192 * MethodHandle[] clause = { init, body, pred, fini }; 5193 * return loop(clause); 5194 * } 5195 * }</pre></blockquote> 5196 * 5197 * @param init optional initializer, providing the initial value of the loop variable. 5198 * May be {@code null}, implying a default initial value. See above for other constraints. 5199 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 5200 * See above for other constraints. 5201 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 5202 * above for other constraints. 5203 * 5204 * @return a method handle implementing the {@code while} loop as described by the arguments. 5205 * @throws IllegalArgumentException if the rules for the arguments are violated. 5206 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 5207 * 5208 * @see #loop(MethodHandle[][]) 5209 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 5210 * @since 9 5211 */ 5212 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 5213 whileLoopChecks(init, pred, body); 5214 MethodHandle fini = identityOrVoid(body.type().returnType()); 5215 MethodHandle[] clause = {init, body, pred, fini }; 5216 return loop(clause); 5217 } 5218 5219 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 5220 Objects.requireNonNull(pred); 5221 Objects.requireNonNull(body); 5222 MethodType bodyType = body.type(); 5223 Class<?> returnType = bodyType.returnType(); 5224 List<Class<?>> innerList = bodyType.parameterList(); 5225 List<Class<?>> outerList = innerList; 5226 if (returnType == void.class) { 5227 // OK 5228 } else if (innerList.size() == 0 || innerList.get(0) != returnType) { 5229 // leading V argument missing => error 5230 MethodType expected = bodyType.insertParameterTypes(0, returnType); 5231 throw misMatchedTypes("body function", bodyType, expected); 5232 } else { 5233 outerList = innerList.subList(1, innerList.size()); 5234 } 5235 MethodType predType = pred.type(); 5236 if (predType.returnType() != boolean.class || 5237 !predType.effectivelyIdenticalParameters(0, innerList)) { 5238 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 5239 } 5240 if (init != null) { 5241 MethodType initType = init.type(); 5242 if (initType.returnType() != returnType || 5243 !initType.effectivelyIdenticalParameters(0, outerList)) { 5244 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 5245 } 5246 } 5247 } 5248 5249 /** 5250 * Constructs a loop that runs a given number of iterations. 5251 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5252 * <p> 5253 * The number of iterations is determined by the {@code iterations} handle evaluation result. 5254 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 5255 * It will be initialized to 0 and incremented by 1 in each iteration. 5256 * <p> 5257 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 5258 * of that type is also present. This variable is initialized using the optional {@code init} handle, 5259 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 5260 * <p> 5261 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 5262 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 5263 * iteration variable. 5264 * The result of the loop handle execution will be the final {@code V} value of that variable 5265 * (or {@code void} if there is no {@code V} variable). 5266 * <p> 5267 * The following rules hold for the argument handles:<ul> 5268 * <li>The {@code iterations} handle must not be {@code null}, and must return 5269 * the type {@code int}, referred to here as {@code I} in parameter type lists. 5270 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5271 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 5272 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5273 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 5274 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 5275 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 5276 * of types called the <em>internal parameter list</em>. 5277 * It will constrain the parameter lists of the other loop parts. 5278 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 5279 * with no additional {@code A} types, then the internal parameter list is extended by 5280 * the argument types {@code A...} of the {@code iterations} handle. 5281 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 5282 * list {@code (A...)} is called the <em>external parameter list</em>. 5283 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5284 * additional state variable of the loop. 5285 * The body must both accept a leading parameter and return a value of this type {@code V}. 5286 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5287 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5288 * <a href="MethodHandles.html#effid">effectively identical</a> 5289 * to the external parameter list {@code (A...)}. 5290 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5291 * {@linkplain #empty default value}. 5292 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 5293 * effectively identical to the external parameter list {@code (A...)}. 5294 * </ul> 5295 * <p> 5296 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5297 * <li>The loop handle's result type is the result type {@code V} of the body. 5298 * <li>The loop handle's parameter types are the types {@code (A...)}, 5299 * from the external parameter list. 5300 * </ul> 5301 * <p> 5302 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5303 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 5304 * arguments passed to the loop. 5305 * <blockquote><pre>{@code 5306 * int iterations(A...); 5307 * V init(A...); 5308 * V body(V, int, A...); 5309 * V countedLoop(A... a...) { 5310 * int end = iterations(a...); 5311 * V v = init(a...); 5312 * for (int i = 0; i < end; ++i) { 5313 * v = body(v, i, a...); 5314 * } 5315 * return v; 5316 * } 5317 * }</pre></blockquote> 5318 * 5319 * @apiNote Example with a fully conformant body method: 5320 * <blockquote><pre>{@code 5321 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 5322 * // => a variation on a well known theme 5323 * static String step(String v, int counter, String init) { return "na " + v; } 5324 * // assume MH_step is a handle to the method above 5325 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 5326 * MethodHandle start = MethodHandles.identity(String.class); 5327 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 5328 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 5329 * }</pre></blockquote> 5330 * 5331 * @apiNote Example with the simplest possible body method type, 5332 * and passing the number of iterations to the loop invocation: 5333 * <blockquote><pre>{@code 5334 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 5335 * // => a variation on a well known theme 5336 * static String step(String v, int counter ) { return "na " + v; } 5337 * // assume MH_step is a handle to the method above 5338 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 5339 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 5340 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 5341 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 5342 * }</pre></blockquote> 5343 * 5344 * @apiNote Example that treats the number of iterations, string to append to, and string to append 5345 * as loop parameters: 5346 * <blockquote><pre>{@code 5347 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 5348 * // => a variation on a well known theme 5349 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 5350 * // assume MH_step is a handle to the method above 5351 * MethodHandle count = MethodHandles.identity(int.class); 5352 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 5353 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 5354 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 5355 * }</pre></blockquote> 5356 * 5357 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 5358 * to enforce a loop type: 5359 * <blockquote><pre>{@code 5360 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 5361 * // => a variation on a well known theme 5362 * static String step(String v, int counter, String pre) { return pre + " " + v; } 5363 * // assume MH_step is a handle to the method above 5364 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 5365 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 5366 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 5367 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 5368 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 5369 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 5370 * }</pre></blockquote> 5371 * 5372 * @apiNote The implementation of this method can be expressed as follows: 5373 * <blockquote><pre>{@code 5374 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 5375 * return countedLoop(empty(iterations.type()), iterations, init, body); 5376 * } 5377 * }</pre></blockquote> 5378 * 5379 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 5380 * result type must be {@code int}. See above for other constraints. 5381 * @param init optional initializer, providing the initial value of the loop variable. 5382 * May be {@code null}, implying a default initial value. See above for other constraints. 5383 * @param body body of the loop, which may not be {@code null}. 5384 * It controls the loop parameters and result type in the standard case (see above for details). 5385 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 5386 * and may accept any number of additional types. 5387 * See above for other constraints. 5388 * 5389 * @return a method handle representing the loop. 5390 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 5391 * @throws IllegalArgumentException if any argument violates the rules formulated above. 5392 * 5393 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 5394 * @since 9 5395 */ 5396 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 5397 return countedLoop(empty(iterations.type()), iterations, init, body); 5398 } 5399 5400 /** 5401 * Constructs a loop that counts over a range of numbers. 5402 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5403 * <p> 5404 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 5405 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 5406 * values of the loop counter. 5407 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 5408 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 5409 * <p> 5410 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 5411 * of that type is also present. This variable is initialized using the optional {@code init} handle, 5412 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 5413 * <p> 5414 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 5415 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 5416 * iteration variable. 5417 * The result of the loop handle execution will be the final {@code V} value of that variable 5418 * (or {@code void} if there is no {@code V} variable). 5419 * <p> 5420 * The following rules hold for the argument handles:<ul> 5421 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 5422 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 5423 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5424 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 5425 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5426 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 5427 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 5428 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 5429 * of types called the <em>internal parameter list</em>. 5430 * It will constrain the parameter lists of the other loop parts. 5431 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 5432 * with no additional {@code A} types, then the internal parameter list is extended by 5433 * the argument types {@code A...} of the {@code end} handle. 5434 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 5435 * list {@code (A...)} is called the <em>external parameter list</em>. 5436 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5437 * additional state variable of the loop. 5438 * The body must both accept a leading parameter and return a value of this type {@code V}. 5439 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5440 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5441 * <a href="MethodHandles.html#effid">effectively identical</a> 5442 * to the external parameter list {@code (A...)}. 5443 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5444 * {@linkplain #empty default value}. 5445 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 5446 * effectively identical to the external parameter list {@code (A...)}. 5447 * <li>Likewise, the parameter list of {@code end} must be effectively identical 5448 * to the external parameter list. 5449 * </ul> 5450 * <p> 5451 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5452 * <li>The loop handle's result type is the result type {@code V} of the body. 5453 * <li>The loop handle's parameter types are the types {@code (A...)}, 5454 * from the external parameter list. 5455 * </ul> 5456 * <p> 5457 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5458 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 5459 * arguments passed to the loop. 5460 * <blockquote><pre>{@code 5461 * int start(A...); 5462 * int end(A...); 5463 * V init(A...); 5464 * V body(V, int, A...); 5465 * V countedLoop(A... a...) { 5466 * int e = end(a...); 5467 * int s = start(a...); 5468 * V v = init(a...); 5469 * for (int i = s; i < e; ++i) { 5470 * v = body(v, i, a...); 5471 * } 5472 * return v; 5473 * } 5474 * }</pre></blockquote> 5475 * 5476 * @apiNote The implementation of this method can be expressed as follows: 5477 * <blockquote><pre>{@code 5478 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 5479 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 5480 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 5481 * // the following semantics: 5482 * // MH_increment: (int limit, int counter) -> counter + 1 5483 * // MH_predicate: (int limit, int counter) -> counter < limit 5484 * Class<?> counterType = start.type().returnType(); // int 5485 * Class<?> returnType = body.type().returnType(); 5486 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 5487 * if (returnType != void.class) { // ignore the V variable 5488 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 5489 * pred = dropArguments(pred, 1, returnType); // ditto 5490 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 5491 * } 5492 * body = dropArguments(body, 0, counterType); // ignore the limit variable 5493 * MethodHandle[] 5494 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 5495 * bodyClause = { init, body }, // v = init(); v = body(v, i) 5496 * indexVar = { start, incr }; // i = start(); i = i + 1 5497 * return loop(loopLimit, bodyClause, indexVar); 5498 * } 5499 * }</pre></blockquote> 5500 * 5501 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 5502 * See above for other constraints. 5503 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 5504 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 5505 * @param init optional initializer, providing the initial value of the loop variable. 5506 * May be {@code null}, implying a default initial value. See above for other constraints. 5507 * @param body body of the loop, which may not be {@code null}. 5508 * It controls the loop parameters and result type in the standard case (see above for details). 5509 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 5510 * and may accept any number of additional types. 5511 * See above for other constraints. 5512 * 5513 * @return a method handle representing the loop. 5514 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 5515 * @throws IllegalArgumentException if any argument violates the rules formulated above. 5516 * 5517 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 5518 * @since 9 5519 */ 5520 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 5521 countedLoopChecks(start, end, init, body); 5522 Class<?> counterType = start.type().returnType(); // int, but who's counting? 5523 Class<?> limitType = end.type().returnType(); // yes, int again 5524 Class<?> returnType = body.type().returnType(); 5525 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 5526 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 5527 MethodHandle retv = null; 5528 if (returnType != void.class) { 5529 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 5530 pred = dropArguments(pred, 1, returnType); // ditto 5531 retv = dropArguments(identity(returnType), 0, counterType); 5532 } 5533 body = dropArguments(body, 0, counterType); // ignore the limit variable 5534 MethodHandle[] 5535 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 5536 bodyClause = { init, body }, // v = init(); v = body(v, i) 5537 indexVar = { start, incr }; // i = start(); i = i + 1 5538 return loop(loopLimit, bodyClause, indexVar); 5539 } 5540 5541 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 5542 Objects.requireNonNull(start); 5543 Objects.requireNonNull(end); 5544 Objects.requireNonNull(body); 5545 Class<?> counterType = start.type().returnType(); 5546 if (counterType != int.class) { 5547 MethodType expected = start.type().changeReturnType(int.class); 5548 throw misMatchedTypes("start function", start.type(), expected); 5549 } else if (end.type().returnType() != counterType) { 5550 MethodType expected = end.type().changeReturnType(counterType); 5551 throw misMatchedTypes("end function", end.type(), expected); 5552 } 5553 MethodType bodyType = body.type(); 5554 Class<?> returnType = bodyType.returnType(); 5555 List<Class<?>> innerList = bodyType.parameterList(); 5556 // strip leading V value if present 5557 int vsize = (returnType == void.class ? 0 : 1); 5558 if (vsize != 0 && (innerList.size() == 0 || innerList.get(0) != returnType)) { 5559 // argument list has no "V" => error 5560 MethodType expected = bodyType.insertParameterTypes(0, returnType); 5561 throw misMatchedTypes("body function", bodyType, expected); 5562 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 5563 // missing I type => error 5564 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 5565 throw misMatchedTypes("body function", bodyType, expected); 5566 } 5567 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 5568 if (outerList.isEmpty()) { 5569 // special case; take lists from end handle 5570 outerList = end.type().parameterList(); 5571 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 5572 } 5573 MethodType expected = methodType(counterType, outerList); 5574 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 5575 throw misMatchedTypes("start parameter types", start.type(), expected); 5576 } 5577 if (end.type() != start.type() && 5578 !end.type().effectivelyIdenticalParameters(0, outerList)) { 5579 throw misMatchedTypes("end parameter types", end.type(), expected); 5580 } 5581 if (init != null) { 5582 MethodType initType = init.type(); 5583 if (initType.returnType() != returnType || 5584 !initType.effectivelyIdenticalParameters(0, outerList)) { 5585 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 5586 } 5587 } 5588 } 5589 5590 /** 5591 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 5592 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5593 * <p> 5594 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 5595 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 5596 * <p> 5597 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 5598 * of that type is also present. This variable is initialized using the optional {@code init} handle, 5599 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 5600 * <p> 5601 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 5602 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 5603 * iteration variable. 5604 * The result of the loop handle execution will be the final {@code V} value of that variable 5605 * (or {@code void} if there is no {@code V} variable). 5606 * <p> 5607 * The following rules hold for the argument handles:<ul> 5608 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5609 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 5610 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5611 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 5612 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 5613 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 5614 * of types called the <em>internal parameter list</em>. 5615 * It will constrain the parameter lists of the other loop parts. 5616 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 5617 * with no additional {@code A} types, then the internal parameter list is extended by 5618 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 5619 * single type {@code Iterable} is added and constitutes the {@code A...} list. 5620 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 5621 * list {@code (A...)} is called the <em>external parameter list</em>. 5622 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5623 * additional state variable of the loop. 5624 * The body must both accept a leading parameter and return a value of this type {@code V}. 5625 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5626 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5627 * <a href="MethodHandles.html#effid">effectively identical</a> 5628 * to the external parameter list {@code (A...)}. 5629 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5630 * {@linkplain #empty default value}. 5631 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 5632 * type {@code java.util.Iterator} or a subtype thereof. 5633 * The iterator it produces when the loop is executed will be assumed 5634 * to yield values which can be converted to type {@code T}. 5635 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 5636 * effectively identical to the external parameter list {@code (A...)}. 5637 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 5638 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 5639 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 5640 * handle parameter is adjusted to accept the leading {@code A} type, as if by 5641 * the {@link MethodHandle#asType asType} conversion method. 5642 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 5643 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 5644 * </ul> 5645 * <p> 5646 * The type {@code T} may be either a primitive or reference. 5647 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 5648 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 5649 * as if by the {@link MethodHandle#asType asType} conversion method. 5650 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 5651 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 5652 * <p> 5653 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5654 * <li>The loop handle's result type is the result type {@code V} of the body. 5655 * <li>The loop handle's parameter types are the types {@code (A...)}, 5656 * from the external parameter list. 5657 * </ul> 5658 * <p> 5659 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5660 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 5661 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 5662 * <blockquote><pre>{@code 5663 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 5664 * V init(A...); 5665 * V body(V,T,A...); 5666 * V iteratedLoop(A... a...) { 5667 * Iterator<T> it = iterator(a...); 5668 * V v = init(a...); 5669 * while (it.hasNext()) { 5670 * T t = it.next(); 5671 * v = body(v, t, a...); 5672 * } 5673 * return v; 5674 * } 5675 * }</pre></blockquote> 5676 * 5677 * @apiNote Example: 5678 * <blockquote><pre>{@code 5679 * // get an iterator from a list 5680 * static List<String> reverseStep(List<String> r, String e) { 5681 * r.add(0, e); 5682 * return r; 5683 * } 5684 * static List<String> newArrayList() { return new ArrayList<>(); } 5685 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 5686 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 5687 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 5688 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 5689 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 5690 * }</pre></blockquote> 5691 * 5692 * @apiNote The implementation of this method can be expressed approximately as follows: 5693 * <blockquote><pre>{@code 5694 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 5695 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 5696 * Class<?> returnType = body.type().returnType(); 5697 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 5698 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 5699 * MethodHandle retv = null, step = body, startIter = iterator; 5700 * if (returnType != void.class) { 5701 * // the simple thing first: in (I V A...), drop the I to get V 5702 * retv = dropArguments(identity(returnType), 0, Iterator.class); 5703 * // body type signature (V T A...), internal loop types (I V A...) 5704 * step = swapArguments(body, 0, 1); // swap V <-> T 5705 * } 5706 * if (startIter == null) startIter = MH_getIter; 5707 * MethodHandle[] 5708 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 5709 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 5710 * return loop(iterVar, bodyClause); 5711 * } 5712 * }</pre></blockquote> 5713 * 5714 * @param iterator an optional handle to return the iterator to start the loop. 5715 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 5716 * See above for other constraints. 5717 * @param init optional initializer, providing the initial value of the loop variable. 5718 * May be {@code null}, implying a default initial value. See above for other constraints. 5719 * @param body body of the loop, which may not be {@code null}. 5720 * It controls the loop parameters and result type in the standard case (see above for details). 5721 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 5722 * and may accept any number of additional types. 5723 * See above for other constraints. 5724 * 5725 * @return a method handle embodying the iteration loop functionality. 5726 * @throws NullPointerException if the {@code body} handle is {@code null}. 5727 * @throws IllegalArgumentException if any argument violates the above requirements. 5728 * 5729 * @since 9 5730 */ 5731 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 5732 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 5733 Class<?> returnType = body.type().returnType(); 5734 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 5735 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 5736 MethodHandle startIter; 5737 MethodHandle nextVal; 5738 { 5739 MethodType iteratorType; 5740 if (iterator == null) { 5741 // derive argument type from body, if available, else use Iterable 5742 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 5743 iteratorType = startIter.type().changeParameterType(0, iterableType); 5744 } else { 5745 // force return type to the internal iterator class 5746 iteratorType = iterator.type().changeReturnType(Iterator.class); 5747 startIter = iterator; 5748 } 5749 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 5750 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 5751 5752 // perform the asType transforms under an exception transformer, as per spec.: 5753 try { 5754 startIter = startIter.asType(iteratorType); 5755 nextVal = nextRaw.asType(nextValType); 5756 } catch (WrongMethodTypeException ex) { 5757 throw new IllegalArgumentException(ex); 5758 } 5759 } 5760 5761 MethodHandle retv = null, step = body; 5762 if (returnType != void.class) { 5763 // the simple thing first: in (I V A...), drop the I to get V 5764 retv = dropArguments(identity(returnType), 0, Iterator.class); 5765 // body type signature (V T A...), internal loop types (I V A...) 5766 step = swapArguments(body, 0, 1); // swap V <-> T 5767 } 5768 5769 MethodHandle[] 5770 iterVar = { startIter, null, hasNext, retv }, 5771 bodyClause = { init, filterArgument(step, 0, nextVal) }; 5772 return loop(iterVar, bodyClause); 5773 } 5774 5775 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 5776 Objects.requireNonNull(body); 5777 MethodType bodyType = body.type(); 5778 Class<?> returnType = bodyType.returnType(); 5779 List<Class<?>> internalParamList = bodyType.parameterList(); 5780 // strip leading V value if present 5781 int vsize = (returnType == void.class ? 0 : 1); 5782 if (vsize != 0 && (internalParamList.size() == 0 || internalParamList.get(0) != returnType)) { 5783 // argument list has no "V" => error 5784 MethodType expected = bodyType.insertParameterTypes(0, returnType); 5785 throw misMatchedTypes("body function", bodyType, expected); 5786 } else if (internalParamList.size() <= vsize) { 5787 // missing T type => error 5788 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 5789 throw misMatchedTypes("body function", bodyType, expected); 5790 } 5791 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 5792 Class<?> iterableType = null; 5793 if (iterator != null) { 5794 // special case; if the body handle only declares V and T then 5795 // the external parameter list is obtained from iterator handle 5796 if (externalParamList.isEmpty()) { 5797 externalParamList = iterator.type().parameterList(); 5798 } 5799 MethodType itype = iterator.type(); 5800 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 5801 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 5802 } 5803 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 5804 MethodType expected = methodType(itype.returnType(), externalParamList); 5805 throw misMatchedTypes("iterator parameters", itype, expected); 5806 } 5807 } else { 5808 if (externalParamList.isEmpty()) { 5809 // special case; if the iterator handle is null and the body handle 5810 // only declares V and T then the external parameter list consists 5811 // of Iterable 5812 externalParamList = Arrays.asList(Iterable.class); 5813 iterableType = Iterable.class; 5814 } else { 5815 // special case; if the iterator handle is null and the external 5816 // parameter list is not empty then the first parameter must be 5817 // assignable to Iterable 5818 iterableType = externalParamList.get(0); 5819 if (!Iterable.class.isAssignableFrom(iterableType)) { 5820 throw newIllegalArgumentException( 5821 "inferred first loop argument must inherit from Iterable: " + iterableType); 5822 } 5823 } 5824 } 5825 if (init != null) { 5826 MethodType initType = init.type(); 5827 if (initType.returnType() != returnType || 5828 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 5829 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 5830 } 5831 } 5832 return iterableType; // help the caller a bit 5833 } 5834 5835 /*non-public*/ static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 5836 // there should be a better way to uncross my wires 5837 int arity = mh.type().parameterCount(); 5838 int[] order = new int[arity]; 5839 for (int k = 0; k < arity; k++) order[k] = k; 5840 order[i] = j; order[j] = i; 5841 Class<?>[] types = mh.type().parameterArray(); 5842 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 5843 MethodType swapType = methodType(mh.type().returnType(), types); 5844 return permuteArguments(mh, swapType, order); 5845 } 5846 5847 /** 5848 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 5849 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 5850 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 5851 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 5852 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 5853 * {@code try-finally} handle. 5854 * <p> 5855 * The {@code cleanup} handle will be passed one or two additional leading arguments. 5856 * The first is the exception thrown during the 5857 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 5858 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 5859 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 5860 * The second argument is not present if the {@code target} handle has a {@code void} return type. 5861 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 5862 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 5863 * <p> 5864 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 5865 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 5866 * two extra leading parameters:<ul> 5867 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 5868 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 5869 * the result from the execution of the {@code target} handle. 5870 * This parameter is not present if the {@code target} returns {@code void}. 5871 * </ul> 5872 * <p> 5873 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 5874 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 5875 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 5876 * the cleanup. 5877 * <blockquote><pre>{@code 5878 * V target(A..., B...); 5879 * V cleanup(Throwable, V, A...); 5880 * V adapter(A... a, B... b) { 5881 * V result = (zero value for V); 5882 * Throwable throwable = null; 5883 * try { 5884 * result = target(a..., b...); 5885 * } catch (Throwable t) { 5886 * throwable = t; 5887 * throw t; 5888 * } finally { 5889 * result = cleanup(throwable, result, a...); 5890 * } 5891 * return result; 5892 * } 5893 * }</pre></blockquote> 5894 * <p> 5895 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 5896 * be modified by execution of the target, and so are passed unchanged 5897 * from the caller to the cleanup, if it is invoked. 5898 * <p> 5899 * The target and cleanup must return the same type, even if the cleanup 5900 * always throws. 5901 * To create such a throwing cleanup, compose the cleanup logic 5902 * with {@link #throwException throwException}, 5903 * in order to create a method handle of the correct return type. 5904 * <p> 5905 * Note that {@code tryFinally} never converts exceptions into normal returns. 5906 * In rare cases where exceptions must be converted in that way, first wrap 5907 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 5908 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 5909 * <p> 5910 * It is recommended that the first parameter type of {@code cleanup} be 5911 * declared {@code Throwable} rather than a narrower subtype. This ensures 5912 * {@code cleanup} will always be invoked with whatever exception that 5913 * {@code target} throws. Declaring a narrower type may result in a 5914 * {@code ClassCastException} being thrown by the {@code try-finally} 5915 * handle if the type of the exception thrown by {@code target} is not 5916 * assignable to the first parameter type of {@code cleanup}. Note that 5917 * various exception types of {@code VirtualMachineError}, 5918 * {@code LinkageError}, and {@code RuntimeException} can in principle be 5919 * thrown by almost any kind of Java code, and a finally clause that 5920 * catches (say) only {@code IOException} would mask any of the others 5921 * behind a {@code ClassCastException}. 5922 * 5923 * @param target the handle whose execution is to be wrapped in a {@code try} block. 5924 * @param cleanup the handle that is invoked in the finally block. 5925 * 5926 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 5927 * @throws NullPointerException if any argument is null 5928 * @throws IllegalArgumentException if {@code cleanup} does not accept 5929 * the required leading arguments, or if the method handle types do 5930 * not match in their return types and their 5931 * corresponding trailing parameters 5932 * 5933 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 5934 * @since 9 5935 */ 5936 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 5937 List<Class<?>> targetParamTypes = target.type().parameterList(); 5938 Class<?> rtype = target.type().returnType(); 5939 5940 tryFinallyChecks(target, cleanup); 5941 5942 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 5943 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 5944 // target parameter list. 5945 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); 5946 5947 // Ensure that the intrinsic type checks the instance thrown by the 5948 // target against the first parameter of cleanup 5949 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 5950 5951 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 5952 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 5953 } 5954 5955 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 5956 Class<?> rtype = target.type().returnType(); 5957 if (rtype != cleanup.type().returnType()) { 5958 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 5959 } 5960 MethodType cleanupType = cleanup.type(); 5961 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 5962 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 5963 } 5964 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 5965 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 5966 } 5967 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 5968 // target parameter list. 5969 int cleanupArgIndex = rtype == void.class ? 1 : 2; 5970 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 5971 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 5972 cleanup.type(), target.type()); 5973 } 5974 } 5975 5976 }