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