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