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