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