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