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