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