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 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED); 2445 } 2446 /** Check access and get the requested constructor. */ 2447 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2448 final boolean checkSecurity = true; 2449 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2450 } 2451 /** Check access and get the requested constructor, eliding security manager checks. */ 2452 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2453 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2454 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2455 } 2456 /** Common code for all constructors; do not call directly except from immediately above. */ 2457 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 2458 boolean checkSecurity) throws IllegalAccessException { 2459 assert(ctor.isConstructor()); 2460 checkAccess(REF_newInvokeSpecial, refc, ctor); 2461 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2462 if (checkSecurity) 2463 checkSecurityManager(refc, ctor); 2464 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 2465 return DirectMethodHandle.make(ctor).setVarargs(ctor); 2466 } 2467 2468 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 2469 */ 2470 /*non-public*/ 2471 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { 2472 if (!(type instanceof Class || type instanceof MethodType)) 2473 throw new InternalError("unresolved MemberName"); 2474 MemberName member = new MemberName(refKind, defc, name, type); 2475 MethodHandle mh = LOOKASIDE_TABLE.get(member); 2476 if (mh != null) { 2477 checkSymbolicClass(defc); 2478 return mh; 2479 } 2480 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 2481 // Treat MethodHandle.invoke and invokeExact specially. 2482 mh = findVirtualForMH(member.getName(), member.getMethodType()); 2483 if (mh != null) { 2484 return mh; 2485 } 2486 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 2487 // Treat signature-polymorphic methods on VarHandle specially. 2488 mh = findVirtualForVH(member.getName(), member.getMethodType()); 2489 if (mh != null) { 2490 return mh; 2491 } 2492 } 2493 MemberName resolved = resolveOrFail(refKind, member); 2494 mh = getDirectMethodForConstant(refKind, defc, resolved); 2495 if (mh instanceof DirectMethodHandle 2496 && canBeCached(refKind, defc, resolved)) { 2497 MemberName key = mh.internalMemberName(); 2498 if (key != null) { 2499 key = key.asNormalOriginal(); 2500 } 2501 if (member.equals(key)) { // better safe than sorry 2502 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 2503 } 2504 } 2505 return mh; 2506 } 2507 private 2508 boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 2509 if (refKind == REF_invokeSpecial) { 2510 return false; 2511 } 2512 if (!Modifier.isPublic(defc.getModifiers()) || 2513 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 2514 !member.isPublic() || 2515 member.isCallerSensitive()) { 2516 return false; 2517 } 2518 ClassLoader loader = defc.getClassLoader(); 2519 if (loader != null) { 2520 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 2521 boolean found = false; 2522 while (sysl != null) { 2523 if (loader == sysl) { found = true; break; } 2524 sysl = sysl.getParent(); 2525 } 2526 if (!found) { 2527 return false; 2528 } 2529 } 2530 try { 2531 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 2532 new MemberName(refKind, defc, member.getName(), member.getType())); 2533 if (resolved2 == null) { 2534 return false; 2535 } 2536 checkSecurityManager(defc, resolved2); 2537 } catch (SecurityException ex) { 2538 return false; 2539 } 2540 return true; 2541 } 2542 private 2543 MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 2544 throws ReflectiveOperationException { 2545 if (MethodHandleNatives.refKindIsField(refKind)) { 2546 return getDirectFieldNoSecurityManager(refKind, defc, member); 2547 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 2548 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); 2549 } else if (refKind == REF_newInvokeSpecial) { 2550 return getDirectConstructorNoSecurityManager(defc, member); 2551 } 2552 // oops 2553 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 2554 } 2555 2556 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 2557 } 2558 2559 /** 2560 * Produces a method handle constructing arrays of a desired type, 2561 * as if by the {@code anewarray} bytecode. 2562 * The return type of the method handle will be the array type. 2563 * The type of its sole argument will be {@code int}, which specifies the size of the array. 2564 * 2565 * <p> If the returned method handle is invoked with a negative 2566 * array size, a {@code NegativeArraySizeException} will be thrown. 2567 * 2568 * @param arrayClass an array type 2569 * @return a method handle which can create arrays of the given type 2570 * @throws NullPointerException if the argument is {@code null} 2571 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 2572 * @see java.lang.reflect.Array#newInstance(Class, int) 2573 * @jvms 6.5 {@code anewarray} Instruction 2574 * @since 9 2575 */ 2576 public static 2577 MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 2578 if (!arrayClass.isArray()) { 2579 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 2580 } 2581 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 2582 bindTo(arrayClass.getComponentType()); 2583 return ani.asType(ani.type().changeReturnType(arrayClass)); 2584 } 2585 2586 /** 2587 * Produces a method handle returning the length of an array, 2588 * as if by the {@code arraylength} bytecode. 2589 * The type of the method handle will have {@code int} as return type, 2590 * and its sole argument will be the array type. 2591 * 2592 * <p> If the returned method handle is invoked with a {@code null} 2593 * array reference, a {@code NullPointerException} will be thrown. 2594 * 2595 * @param arrayClass an array type 2596 * @return a method handle which can retrieve the length of an array of the given array type 2597 * @throws NullPointerException if the argument is {@code null} 2598 * @throws IllegalArgumentException if arrayClass is not an array type 2599 * @jvms 6.5 {@code arraylength} Instruction 2600 * @since 9 2601 */ 2602 public static 2603 MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 2604 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 2605 } 2606 2607 /** 2608 * Produces a method handle giving read access to elements of an array, 2609 * as if by the {@code aaload} bytecode. 2610 * The type of the method handle will have a return type of the array's 2611 * element type. Its first argument will be the array type, 2612 * and the second will be {@code int}. 2613 * 2614 * <p> When the returned method handle is invoked, 2615 * the array reference and array index are checked. 2616 * A {@code NullPointerException} will be thrown if the array reference 2617 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 2618 * thrown if the index is negative or if it is greater than or equal to 2619 * the length of the array. 2620 * 2621 * @param arrayClass an array type 2622 * @return a method handle which can load values from the given array type 2623 * @throws NullPointerException if the argument is null 2624 * @throws IllegalArgumentException if arrayClass is not an array type 2625 * @jvms 6.5 {@code aaload} Instruction 2626 */ 2627 public static 2628 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 2629 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 2630 } 2631 2632 /** 2633 * Produces a method handle giving write access to elements of an array, 2634 * as if by the {@code astore} bytecode. 2635 * The type of the method handle will have a void return type. 2636 * Its last argument will be the array's element type. 2637 * The first and second arguments will be the array type and int. 2638 * 2639 * <p> When the returned method handle is invoked, 2640 * the array reference and array index are checked. 2641 * A {@code NullPointerException} will be thrown if the array reference 2642 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 2643 * thrown if the index is negative or if it is greater than or equal to 2644 * the length of the array. 2645 * 2646 * @param arrayClass the class of an array 2647 * @return a method handle which can store values into the array type 2648 * @throws NullPointerException if the argument is null 2649 * @throws IllegalArgumentException if arrayClass is not an array type 2650 * @jvms 6.5 {@code aastore} Instruction 2651 */ 2652 public static 2653 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 2654 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 2655 } 2656 2657 /** 2658 * Produces a VarHandle giving access to elements of an array of type 2659 * {@code arrayClass}. The VarHandle's variable type is the component type 2660 * of {@code arrayClass} and the list of coordinate types is 2661 * {@code (arrayClass, int)}, where the {@code int} coordinate type 2662 * corresponds to an argument that is an index into an array. 2663 * <p> 2664 * Certain access modes of the returned VarHandle are unsupported under 2665 * the following conditions: 2666 * <ul> 2667 * <li>if the component type is anything other than {@code byte}, 2668 * {@code short}, {@code char}, {@code int}, {@code long}, 2669 * {@code float}, or {@code double} then numeric atomic update access 2670 * modes are unsupported. 2671 * <li>if the field type is anything other than {@code boolean}, 2672 * {@code byte}, {@code short}, {@code char}, {@code int} or 2673 * {@code long} then bitwise atomic update access modes are 2674 * unsupported. 2675 * </ul> 2676 * <p> 2677 * If the component type is {@code float} or {@code double} then numeric 2678 * and atomic update access modes compare values using their bitwise 2679 * representation (see {@link Float#floatToRawIntBits} and 2680 * {@link Double#doubleToRawLongBits}, respectively). 2681 * 2682 * <p> When the returned {@code VarHandle} is invoked, 2683 * the array reference and array index are checked. 2684 * A {@code NullPointerException} will be thrown if the array reference 2685 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 2686 * thrown if the index is negative or if it is greater than or equal to 2687 * the length of the array. 2688 * 2689 * @apiNote 2690 * Bitwise comparison of {@code float} values or {@code double} values, 2691 * as performed by the numeric and atomic update access modes, differ 2692 * from the primitive {@code ==} operator and the {@link Float#equals} 2693 * and {@link Double#equals} methods, specifically with respect to 2694 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 2695 * Care should be taken when performing a compare and set or a compare 2696 * and exchange operation with such values since the operation may 2697 * unexpectedly fail. 2698 * There are many possible NaN values that are considered to be 2699 * {@code NaN} in Java, although no IEEE 754 floating-point operation 2700 * provided by Java can distinguish between them. Operation failure can 2701 * occur if the expected or witness value is a NaN value and it is 2702 * transformed (perhaps in a platform specific manner) into another NaN 2703 * value, and thus has a different bitwise representation (see 2704 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 2705 * details). 2706 * The values {@code -0.0} and {@code +0.0} have different bitwise 2707 * representations but are considered equal when using the primitive 2708 * {@code ==} operator. Operation failure can occur if, for example, a 2709 * numeric algorithm computes an expected value to be say {@code -0.0} 2710 * and previously computed the witness value to be say {@code +0.0}. 2711 * @param arrayClass the class of an array, of type {@code T[]} 2712 * @return a VarHandle giving access to elements of an array 2713 * @throws NullPointerException if the arrayClass is null 2714 * @throws IllegalArgumentException if arrayClass is not an array type 2715 * @since 9 2716 */ 2717 public static 2718 VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 2719 return VarHandles.makeArrayElementHandle(arrayClass); 2720 } 2721 2722 /** 2723 * Produces a VarHandle giving access to elements of a {@code byte[]} array 2724 * viewed as if it were a different primitive array type, such as 2725 * {@code int[]} or {@code long[]}. 2726 * The VarHandle's variable type is the component type of 2727 * {@code viewArrayClass} and the list of coordinate types is 2728 * {@code (byte[], int)}, where the {@code int} coordinate type 2729 * corresponds to an argument that is an index into a {@code byte[]} array. 2730 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 2731 * array, composing bytes to or from a value of the component type of 2732 * {@code viewArrayClass} according to the given endianness. 2733 * <p> 2734 * The supported component types (variables types) are {@code short}, 2735 * {@code char}, {@code int}, {@code long}, {@code float} and 2736 * {@code double}. 2737 * <p> 2738 * Access of bytes at a given index will result in an 2739 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2740 * or greater than the {@code byte[]} array length minus the size (in bytes) 2741 * of {@code T}. 2742 * <p> 2743 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2744 * with respect to the underlying memory address, {@code A} say, associated 2745 * with the array and index. 2746 * If access is misaligned then access for anything other than the 2747 * {@code get} and {@code set} access modes will result in an 2748 * {@code IllegalStateException}. In such cases atomic access is only 2749 * guaranteed with respect to the largest power of two that divides the GCD 2750 * of {@code A} and the size (in bytes) of {@code T}. 2751 * If access is aligned then following access modes are supported and are 2752 * guaranteed to support atomic access: 2753 * <ul> 2754 * <li>read write access modes for all {@code T}, with the exception of 2755 * access modes {@code get} and {@code set} for {@code long} and 2756 * {@code double} on 32-bit platforms. 2757 * <li>atomic update access modes for {@code int}, {@code long}, 2758 * {@code float} or {@code double}. 2759 * (Future major platform releases of the JDK may support additional 2760 * types for certain currently unsupported access modes.) 2761 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2762 * (Future major platform releases of the JDK may support additional 2763 * numeric types for certain currently unsupported access modes.) 2764 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 2765 * (Future major platform releases of the JDK may support additional 2766 * numeric types for certain currently unsupported access modes.) 2767 * </ul> 2768 * <p> 2769 * Misaligned access, and therefore atomicity guarantees, may be determined 2770 * for {@code byte[]} arrays without operating on a specific array. Given 2771 * an {@code index}, {@code T} and it's corresponding boxed type, 2772 * {@code T_BOX}, misalignment may be determined as follows: 2773 * <pre>{@code 2774 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2775 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 2776 * alignmentOffset(0, sizeOfT); 2777 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 2778 * boolean isMisaligned = misalignedAtIndex != 0; 2779 * }</pre> 2780 * <p> 2781 * If the variable type is {@code float} or {@code double} then atomic 2782 * update access modes compare values using their bitwise representation 2783 * (see {@link Float#floatToRawIntBits} and 2784 * {@link Double#doubleToRawLongBits}, respectively). 2785 * @param viewArrayClass the view array class, with a component type of 2786 * type {@code T} 2787 * @param byteOrder the endianness of the view array elements, as 2788 * stored in the underlying {@code byte} array 2789 * @return a VarHandle giving access to elements of a {@code byte[]} array 2790 * viewed as if elements corresponding to the components type of the view 2791 * array class 2792 * @throws NullPointerException if viewArrayClass or byteOrder is null 2793 * @throws IllegalArgumentException if viewArrayClass is not an array type 2794 * @throws UnsupportedOperationException if the component type of 2795 * viewArrayClass is not supported as a variable type 2796 * @since 9 2797 */ 2798 public static 2799 VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 2800 ByteOrder byteOrder) throws IllegalArgumentException { 2801 Objects.requireNonNull(byteOrder); 2802 return VarHandles.byteArrayViewHandle(viewArrayClass, 2803 byteOrder == ByteOrder.BIG_ENDIAN); 2804 } 2805 2806 /** 2807 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 2808 * viewed as if it were an array of elements of a different primitive 2809 * component type to that of {@code byte}, such as {@code int[]} or 2810 * {@code long[]}. 2811 * The VarHandle's variable type is the component type of 2812 * {@code viewArrayClass} and the list of coordinate types is 2813 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 2814 * corresponds to an argument that is an index into a {@code byte[]} array. 2815 * The returned VarHandle accesses bytes at an index in a 2816 * {@code ByteBuffer}, composing bytes to or from a value of the component 2817 * type of {@code viewArrayClass} according to the given endianness. 2818 * <p> 2819 * The supported component types (variables types) are {@code short}, 2820 * {@code char}, {@code int}, {@code long}, {@code float} and 2821 * {@code double}. 2822 * <p> 2823 * Access will result in a {@code ReadOnlyBufferException} for anything 2824 * other than the read access modes if the {@code ByteBuffer} is read-only. 2825 * <p> 2826 * Access of bytes at a given index will result in an 2827 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2828 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 2829 * {@code T}. 2830 * <p> 2831 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2832 * with respect to the underlying memory address, {@code A} say, associated 2833 * with the {@code ByteBuffer} and index. 2834 * If access is misaligned then access for anything other than the 2835 * {@code get} and {@code set} access modes will result in an 2836 * {@code IllegalStateException}. In such cases atomic access is only 2837 * guaranteed with respect to the largest power of two that divides the GCD 2838 * of {@code A} and the size (in bytes) of {@code T}. 2839 * If access is aligned then following access modes are supported and are 2840 * guaranteed to support atomic access: 2841 * <ul> 2842 * <li>read write access modes for all {@code T}, with the exception of 2843 * access modes {@code get} and {@code set} for {@code long} and 2844 * {@code double} on 32-bit platforms. 2845 * <li>atomic update access modes for {@code int}, {@code long}, 2846 * {@code float} or {@code double}. 2847 * (Future major platform releases of the JDK may support additional 2848 * types for certain currently unsupported access modes.) 2849 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2850 * (Future major platform releases of the JDK may support additional 2851 * numeric types for certain currently unsupported access modes.) 2852 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 2853 * (Future major platform releases of the JDK may support additional 2854 * numeric types for certain currently unsupported access modes.) 2855 * </ul> 2856 * <p> 2857 * Misaligned access, and therefore atomicity guarantees, may be determined 2858 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 2859 * {@code index}, {@code T} and it's corresponding boxed type, 2860 * {@code T_BOX}, as follows: 2861 * <pre>{@code 2862 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2863 * ByteBuffer bb = ... 2864 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 2865 * boolean isMisaligned = misalignedAtIndex != 0; 2866 * }</pre> 2867 * <p> 2868 * If the variable type is {@code float} or {@code double} then atomic 2869 * update access modes compare values using their bitwise representation 2870 * (see {@link Float#floatToRawIntBits} and 2871 * {@link Double#doubleToRawLongBits}, respectively). 2872 * @param viewArrayClass the view array class, with a component type of 2873 * type {@code T} 2874 * @param byteOrder the endianness of the view array elements, as 2875 * stored in the underlying {@code ByteBuffer} (Note this overrides the 2876 * endianness of a {@code ByteBuffer}) 2877 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 2878 * viewed as if elements corresponding to the components type of the view 2879 * array class 2880 * @throws NullPointerException if viewArrayClass or byteOrder is null 2881 * @throws IllegalArgumentException if viewArrayClass is not an array type 2882 * @throws UnsupportedOperationException if the component type of 2883 * viewArrayClass is not supported as a variable type 2884 * @since 9 2885 */ 2886 public static 2887 VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 2888 ByteOrder byteOrder) throws IllegalArgumentException { 2889 Objects.requireNonNull(byteOrder); 2890 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 2891 byteOrder == ByteOrder.BIG_ENDIAN); 2892 } 2893 2894 2895 /// method handle invocation (reflective style) 2896 2897 /** 2898 * Produces a method handle which will invoke any method handle of the 2899 * given {@code type}, with a given number of trailing arguments replaced by 2900 * a single trailing {@code Object[]} array. 2901 * The resulting invoker will be a method handle with the following 2902 * arguments: 2903 * <ul> 2904 * <li>a single {@code MethodHandle} target 2905 * <li>zero or more leading values (counted by {@code leadingArgCount}) 2906 * <li>an {@code Object[]} array containing trailing arguments 2907 * </ul> 2908 * <p> 2909 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 2910 * the indicated {@code type}. 2911 * That is, if the target is exactly of the given {@code type}, it will behave 2912 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 2913 * is used to convert the target to the required {@code type}. 2914 * <p> 2915 * The type of the returned invoker will not be the given {@code type}, but rather 2916 * will have all parameters except the first {@code leadingArgCount} 2917 * replaced by a single array of type {@code Object[]}, which will be 2918 * the final parameter. 2919 * <p> 2920 * Before invoking its target, the invoker will spread the final array, apply 2921 * reference casts as necessary, and unbox and widen primitive arguments. 2922 * If, when the invoker is called, the supplied array argument does 2923 * not have the correct number of elements, the invoker will throw 2924 * an {@link IllegalArgumentException} instead of invoking the target. 2925 * <p> 2926 * This method is equivalent to the following code (though it may be more efficient): 2927 * <blockquote><pre>{@code 2928 MethodHandle invoker = MethodHandles.invoker(type); 2929 int spreadArgCount = type.parameterCount() - leadingArgCount; 2930 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 2931 return invoker; 2932 * }</pre></blockquote> 2933 * This method throws no reflective or security exceptions. 2934 * @param type the desired target type 2935 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 2936 * @return a method handle suitable for invoking any method handle of the given type 2937 * @throws NullPointerException if {@code type} is null 2938 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 2939 * the range from 0 to {@code type.parameterCount()} inclusive, 2940 * or if the resulting method handle's type would have 2941 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2942 */ 2943 public static 2944 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 2945 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 2946 throw newIllegalArgumentException("bad argument count", leadingArgCount); 2947 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 2948 return type.invokers().spreadInvoker(leadingArgCount); 2949 } 2950 2951 /** 2952 * Produces a special <em>invoker method handle</em> which can be used to 2953 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 2954 * The resulting invoker will have a type which is 2955 * exactly equal to the desired type, except that it will accept 2956 * an additional leading argument of type {@code MethodHandle}. 2957 * <p> 2958 * This method is equivalent to the following code (though it may be more efficient): 2959 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 2960 * 2961 * <p style="font-size:smaller;"> 2962 * <em>Discussion:</em> 2963 * Invoker method handles can be useful when working with variable method handles 2964 * of unknown types. 2965 * For example, to emulate an {@code invokeExact} call to a variable method 2966 * handle {@code M}, extract its type {@code T}, 2967 * look up the invoker method {@code X} for {@code T}, 2968 * and call the invoker method, as {@code X.invoke(T, A...)}. 2969 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 2970 * is unknown.) 2971 * If spreading, collecting, or other argument transformations are required, 2972 * they can be applied once to the invoker {@code X} and reused on many {@code M} 2973 * method handle values, as long as they are compatible with the type of {@code X}. 2974 * <p style="font-size:smaller;"> 2975 * <em>(Note: The invoker method is not available via the Core Reflection API. 2976 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2977 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2978 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2979 * <p> 2980 * This method throws no reflective or security exceptions. 2981 * @param type the desired target type 2982 * @return a method handle suitable for invoking any method handle of the given type 2983 * @throws IllegalArgumentException if the resulting method handle's type would have 2984 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2985 */ 2986 public static 2987 MethodHandle exactInvoker(MethodType type) { 2988 return type.invokers().exactInvoker(); 2989 } 2990 2991 /** 2992 * Produces a special <em>invoker method handle</em> which can be used to 2993 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 2994 * The resulting invoker will have a type which is 2995 * exactly equal to the desired type, except that it will accept 2996 * an additional leading argument of type {@code MethodHandle}. 2997 * <p> 2998 * Before invoking its target, if the target differs from the expected type, 2999 * the invoker will apply reference casts as 3000 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 3001 * Similarly, the return value will be converted as necessary. 3002 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 3003 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 3004 * <p> 3005 * This method is equivalent to the following code (though it may be more efficient): 3006 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 3007 * <p style="font-size:smaller;"> 3008 * <em>Discussion:</em> 3009 * A {@linkplain MethodType#genericMethodType general method type} is one which 3010 * mentions only {@code Object} arguments and return values. 3011 * An invoker for such a type is capable of calling any method handle 3012 * of the same arity as the general type. 3013 * <p style="font-size:smaller;"> 3014 * <em>(Note: The invoker method is not available via the Core Reflection API. 3015 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 3016 * on the declared {@code invokeExact} or {@code invoke} method will raise an 3017 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 3018 * <p> 3019 * This method throws no reflective or security exceptions. 3020 * @param type the desired target type 3021 * @return a method handle suitable for invoking any method handle convertible to the given type 3022 * @throws IllegalArgumentException if the resulting method handle's type would have 3023 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3024 */ 3025 public static 3026 MethodHandle invoker(MethodType type) { 3027 return type.invokers().genericInvoker(); 3028 } 3029 3030 /** 3031 * Produces a special <em>invoker method handle</em> which can be used to 3032 * invoke a signature-polymorphic access mode method on any VarHandle whose 3033 * associated access mode type is compatible with the given type. 3034 * The resulting invoker will have a type which is exactly equal to the 3035 * desired given type, except that it will accept an additional leading 3036 * argument of type {@code VarHandle}. 3037 * 3038 * @param accessMode the VarHandle access mode 3039 * @param type the desired target type 3040 * @return a method handle suitable for invoking an access mode method of 3041 * any VarHandle whose access mode type is of the given type. 3042 * @since 9 3043 */ 3044 static public 3045 MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 3046 return type.invokers().varHandleMethodExactInvoker(accessMode); 3047 } 3048 3049 /** 3050 * Produces a special <em>invoker method handle</em> which can be used to 3051 * invoke a signature-polymorphic access mode method on any VarHandle whose 3052 * associated access mode type is compatible with the given type. 3053 * The resulting invoker will have a type which is exactly equal to the 3054 * desired given type, except that it will accept an additional leading 3055 * argument of type {@code VarHandle}. 3056 * <p> 3057 * Before invoking its target, if the access mode type differs from the 3058 * desired given type, the invoker will apply reference casts as necessary 3059 * and box, unbox, or widen primitive values, as if by 3060 * {@link MethodHandle#asType asType}. Similarly, the return value will be 3061 * converted as necessary. 3062 * <p> 3063 * This method is equivalent to the following code (though it may be more 3064 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 3065 * 3066 * @param accessMode the VarHandle access mode 3067 * @param type the desired target type 3068 * @return a method handle suitable for invoking an access mode method of 3069 * any VarHandle whose access mode type is convertible to the given 3070 * type. 3071 * @since 9 3072 */ 3073 static public 3074 MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 3075 return type.invokers().varHandleMethodInvoker(accessMode); 3076 } 3077 3078 static /*non-public*/ 3079 MethodHandle basicInvoker(MethodType type) { 3080 return type.invokers().basicInvoker(); 3081 } 3082 3083 /// method handle modification (creation from other method handles) 3084 3085 /** 3086 * Produces a method handle which adapts the type of the 3087 * given method handle to a new type by pairwise argument and return type conversion. 3088 * The original type and new type must have the same number of arguments. 3089 * The resulting method handle is guaranteed to report a type 3090 * which is equal to the desired new type. 3091 * <p> 3092 * If the original type and new type are equal, returns target. 3093 * <p> 3094 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 3095 * and some additional conversions are also applied if those conversions fail. 3096 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 3097 * if possible, before or instead of any conversions done by {@code asType}: 3098 * <ul> 3099 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 3100 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 3101 * (This treatment of interfaces follows the usage of the bytecode verifier.) 3102 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 3103 * the boolean is converted to a byte value, 1 for true, 0 for false. 3104 * (This treatment follows the usage of the bytecode verifier.) 3105 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 3106 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 3107 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 3108 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 3109 * then a Java casting conversion (JLS 5.5) is applied. 3110 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 3111 * widening and/or narrowing.) 3112 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 3113 * conversion will be applied at runtime, possibly followed 3114 * by a Java casting conversion (JLS 5.5) on the primitive value, 3115 * possibly followed by a conversion from byte to boolean by testing 3116 * the low-order bit. 3117 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 3118 * and if the reference is null at runtime, a zero value is introduced. 3119 * </ul> 3120 * @param target the method handle to invoke after arguments are retyped 3121 * @param newType the expected type of the new method handle 3122 * @return a method handle which delegates to the target after performing 3123 * any necessary argument conversions, and arranges for any 3124 * necessary return value conversions 3125 * @throws NullPointerException if either argument is null 3126 * @throws WrongMethodTypeException if the conversion cannot be made 3127 * @see MethodHandle#asType 3128 */ 3129 public static 3130 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 3131 explicitCastArgumentsChecks(target, newType); 3132 // use the asTypeCache when possible: 3133 MethodType oldType = target.type(); 3134 if (oldType == newType) return target; 3135 if (oldType.explicitCastEquivalentToAsType(newType)) { 3136 return target.asFixedArity().asType(newType); 3137 } 3138 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 3139 } 3140 3141 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 3142 if (target.type().parameterCount() != newType.parameterCount()) { 3143 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 3144 } 3145 } 3146 3147 /** 3148 * Produces a method handle which adapts the calling sequence of the 3149 * given method handle to a new type, by reordering the arguments. 3150 * The resulting method handle is guaranteed to report a type 3151 * which is equal to the desired new type. 3152 * <p> 3153 * The given array controls the reordering. 3154 * Call {@code #I} the number of incoming parameters (the value 3155 * {@code newType.parameterCount()}, and call {@code #O} the number 3156 * of outgoing parameters (the value {@code target.type().parameterCount()}). 3157 * Then the length of the reordering array must be {@code #O}, 3158 * and each element must be a non-negative number less than {@code #I}. 3159 * For every {@code N} less than {@code #O}, the {@code N}-th 3160 * outgoing argument will be taken from the {@code I}-th incoming 3161 * argument, where {@code I} is {@code reorder[N]}. 3162 * <p> 3163 * No argument or return value conversions are applied. 3164 * The type of each incoming argument, as determined by {@code newType}, 3165 * must be identical to the type of the corresponding outgoing parameter 3166 * or parameters in the target method handle. 3167 * The return type of {@code newType} must be identical to the return 3168 * type of the original target. 3169 * <p> 3170 * The reordering array need not specify an actual permutation. 3171 * An incoming argument will be duplicated if its index appears 3172 * more than once in the array, and an incoming argument will be dropped 3173 * if its index does not appear in the array. 3174 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 3175 * incoming arguments which are not mentioned in the reordering array 3176 * may be of any type, as determined only by {@code newType}. 3177 * <blockquote><pre>{@code 3178 import static java.lang.invoke.MethodHandles.*; 3179 import static java.lang.invoke.MethodType.*; 3180 ... 3181 MethodType intfn1 = methodType(int.class, int.class); 3182 MethodType intfn2 = methodType(int.class, int.class, int.class); 3183 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 3184 assert(sub.type().equals(intfn2)); 3185 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 3186 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 3187 assert((int)rsub.invokeExact(1, 100) == 99); 3188 MethodHandle add = ... (int x, int y) -> (x+y) ...; 3189 assert(add.type().equals(intfn2)); 3190 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 3191 assert(twice.type().equals(intfn1)); 3192 assert((int)twice.invokeExact(21) == 42); 3193 * }</pre></blockquote> 3194 * <p> 3195 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3196 * variable-arity method handle}, even if the original target method handle was. 3197 * @param target the method handle to invoke after arguments are reordered 3198 * @param newType the expected type of the new method handle 3199 * @param reorder an index array which controls the reordering 3200 * @return a method handle which delegates to the target after it 3201 * drops unused arguments and moves and/or duplicates the other arguments 3202 * @throws NullPointerException if any argument is null 3203 * @throws IllegalArgumentException if the index array length is not equal to 3204 * the arity of the target, or if any index array element 3205 * not a valid index for a parameter of {@code newType}, 3206 * or if two corresponding parameter types in 3207 * {@code target.type()} and {@code newType} are not identical, 3208 */ 3209 public static 3210 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 3211 reorder = reorder.clone(); // get a private copy 3212 MethodType oldType = target.type(); 3213 permuteArgumentChecks(reorder, newType, oldType); 3214 // first detect dropped arguments and handle them separately 3215 int[] originalReorder = reorder; 3216 BoundMethodHandle result = target.rebind(); 3217 LambdaForm form = result.form; 3218 int newArity = newType.parameterCount(); 3219 // Normalize the reordering into a real permutation, 3220 // by removing duplicates and adding dropped elements. 3221 // This somewhat improves lambda form caching, as well 3222 // as simplifying the transform by breaking it up into steps. 3223 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 3224 if (ddIdx > 0) { 3225 // We found a duplicated entry at reorder[ddIdx]. 3226 // Example: (x,y,z)->asList(x,y,z) 3227 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 3228 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 3229 // The starred element corresponds to the argument 3230 // deleted by the dupArgumentForm transform. 3231 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 3232 boolean killFirst = false; 3233 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 3234 // Set killFirst if the dup is larger than an intervening position. 3235 // This will remove at least one inversion from the permutation. 3236 if (dupVal > val) killFirst = true; 3237 } 3238 if (!killFirst) { 3239 srcPos = dstPos; 3240 dstPos = ddIdx; 3241 } 3242 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 3243 assert (reorder[srcPos] == reorder[dstPos]); 3244 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 3245 // contract the reordering by removing the element at dstPos 3246 int tailPos = dstPos + 1; 3247 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 3248 reorder = Arrays.copyOf(reorder, reorder.length - 1); 3249 } else { 3250 int dropVal = ~ddIdx, insPos = 0; 3251 while (insPos < reorder.length && reorder[insPos] < dropVal) { 3252 // Find first element of reorder larger than dropVal. 3253 // This is where we will insert the dropVal. 3254 insPos += 1; 3255 } 3256 Class<?> ptype = newType.parameterType(dropVal); 3257 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 3258 oldType = oldType.insertParameterTypes(insPos, ptype); 3259 // expand the reordering by inserting an element at insPos 3260 int tailPos = insPos + 1; 3261 reorder = Arrays.copyOf(reorder, reorder.length + 1); 3262 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 3263 reorder[insPos] = dropVal; 3264 } 3265 assert (permuteArgumentChecks(reorder, newType, oldType)); 3266 } 3267 assert (reorder.length == newArity); // a perfect permutation 3268 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 3269 form = form.editor().permuteArgumentsForm(1, reorder); 3270 if (newType == result.type() && form == result.internalForm()) 3271 return result; 3272 return result.copyWith(newType, form); 3273 } 3274 3275 /** 3276 * Return an indication of any duplicate or omission in reorder. 3277 * If the reorder contains a duplicate entry, return the index of the second occurrence. 3278 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 3279 * Otherwise, return zero. 3280 * If an element not in [0..newArity-1] is encountered, return reorder.length. 3281 */ 3282 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 3283 final int BIT_LIMIT = 63; // max number of bits in bit mask 3284 if (newArity < BIT_LIMIT) { 3285 long mask = 0; 3286 for (int i = 0; i < reorder.length; i++) { 3287 int arg = reorder[i]; 3288 if (arg >= newArity) { 3289 return reorder.length; 3290 } 3291 long bit = 1L << arg; 3292 if ((mask & bit) != 0) { 3293 return i; // >0 indicates a dup 3294 } 3295 mask |= bit; 3296 } 3297 if (mask == (1L << newArity) - 1) { 3298 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 3299 return 0; 3300 } 3301 // find first zero 3302 long zeroBit = Long.lowestOneBit(~mask); 3303 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 3304 assert(zeroPos <= newArity); 3305 if (zeroPos == newArity) { 3306 return 0; 3307 } 3308 return ~zeroPos; 3309 } else { 3310 // same algorithm, different bit set 3311 BitSet mask = new BitSet(newArity); 3312 for (int i = 0; i < reorder.length; i++) { 3313 int arg = reorder[i]; 3314 if (arg >= newArity) { 3315 return reorder.length; 3316 } 3317 if (mask.get(arg)) { 3318 return i; // >0 indicates a dup 3319 } 3320 mask.set(arg); 3321 } 3322 int zeroPos = mask.nextClearBit(0); 3323 assert(zeroPos <= newArity); 3324 if (zeroPos == newArity) { 3325 return 0; 3326 } 3327 return ~zeroPos; 3328 } 3329 } 3330 3331 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 3332 if (newType.returnType() != oldType.returnType()) 3333 throw newIllegalArgumentException("return types do not match", 3334 oldType, newType); 3335 if (reorder.length == oldType.parameterCount()) { 3336 int limit = newType.parameterCount(); 3337 boolean bad = false; 3338 for (int j = 0; j < reorder.length; j++) { 3339 int i = reorder[j]; 3340 if (i < 0 || i >= limit) { 3341 bad = true; break; 3342 } 3343 Class<?> src = newType.parameterType(i); 3344 Class<?> dst = oldType.parameterType(j); 3345 if (src != dst) 3346 throw newIllegalArgumentException("parameter types do not match after reorder", 3347 oldType, newType); 3348 } 3349 if (!bad) return true; 3350 } 3351 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 3352 } 3353 3354 /** 3355 * Produces a method handle of the requested return type which returns the given 3356 * constant value every time it is invoked. 3357 * <p> 3358 * Before the method handle is returned, the passed-in value is converted to the requested type. 3359 * If the requested type is primitive, widening primitive conversions are attempted, 3360 * else reference conversions are attempted. 3361 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 3362 * @param type the return type of the desired method handle 3363 * @param value the value to return 3364 * @return a method handle of the given return type and no arguments, which always returns the given value 3365 * @throws NullPointerException if the {@code type} argument is null 3366 * @throws ClassCastException if the value cannot be converted to the required return type 3367 * @throws IllegalArgumentException if the given type is {@code void.class} 3368 */ 3369 public static 3370 MethodHandle constant(Class<?> type, Object value) { 3371 if (type.isPrimitive()) { 3372 if (type == void.class) 3373 throw newIllegalArgumentException("void type"); 3374 Wrapper w = Wrapper.forPrimitiveType(type); 3375 value = w.convert(value, type); 3376 if (w.zero().equals(value)) 3377 return zero(w, type); 3378 return insertArguments(identity(type), 0, value); 3379 } else { 3380 if (value == null) 3381 return zero(Wrapper.OBJECT, type); 3382 return identity(type).bindTo(value); 3383 } 3384 } 3385 3386 /** 3387 * Produces a method handle which returns its sole argument when invoked. 3388 * @param type the type of the sole parameter and return value of the desired method handle 3389 * @return a unary method handle which accepts and returns the given type 3390 * @throws NullPointerException if the argument is null 3391 * @throws IllegalArgumentException if the given type is {@code void.class} 3392 */ 3393 public static 3394 MethodHandle identity(Class<?> type) { 3395 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 3396 int pos = btw.ordinal(); 3397 MethodHandle ident = IDENTITY_MHS[pos]; 3398 if (ident == null) { 3399 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 3400 } 3401 if (ident.type().returnType() == type) 3402 return ident; 3403 // something like identity(Foo.class); do not bother to intern these 3404 assert (btw == Wrapper.OBJECT); 3405 return makeIdentity(type); 3406 } 3407 3408 /** 3409 * Produces a constant method handle of the requested return type which 3410 * returns the default value for that type every time it is invoked. 3411 * The resulting constant method handle will have no side effects. 3412 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 3413 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 3414 * since {@code explicitCastArguments} converts {@code null} to default values. 3415 * @param type the expected return type of the desired method handle 3416 * @return a constant method handle that takes no arguments 3417 * and returns the default value of the given type (or void, if the type is void) 3418 * @throws NullPointerException if the argument is null 3419 * @see MethodHandles#constant 3420 * @see MethodHandles#empty 3421 * @see MethodHandles#explicitCastArguments 3422 * @since 9 3423 */ 3424 public static MethodHandle zero(Class<?> type) { 3425 Objects.requireNonNull(type); 3426 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 3427 } 3428 3429 private static MethodHandle identityOrVoid(Class<?> type) { 3430 return type == void.class ? zero(type) : identity(type); 3431 } 3432 3433 /** 3434 * Produces a method handle of the requested type which ignores any arguments, does nothing, 3435 * and returns a suitable default depending on the return type. 3436 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 3437 * <p>The returned method handle is equivalent to 3438 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 3439 * 3440 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 3441 * {@code guardWithTest(pred, target, empty(target.type())}. 3442 * @param type the type of the desired method handle 3443 * @return a constant method handle of the given type, which returns a default value of the given return type 3444 * @throws NullPointerException if the argument is null 3445 * @see MethodHandles#zero 3446 * @see MethodHandles#constant 3447 * @since 9 3448 */ 3449 public static MethodHandle empty(MethodType type) { 3450 Objects.requireNonNull(type); 3451 return dropArguments(zero(type.returnType()), 0, type.parameterList()); 3452 } 3453 3454 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 3455 private static MethodHandle makeIdentity(Class<?> ptype) { 3456 MethodType mtype = methodType(ptype, ptype); 3457 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 3458 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 3459 } 3460 3461 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 3462 int pos = btw.ordinal(); 3463 MethodHandle zero = ZERO_MHS[pos]; 3464 if (zero == null) { 3465 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 3466 } 3467 if (zero.type().returnType() == rtype) 3468 return zero; 3469 assert(btw == Wrapper.OBJECT); 3470 return makeZero(rtype); 3471 } 3472 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 3473 private static MethodHandle makeZero(Class<?> rtype) { 3474 MethodType mtype = methodType(rtype); 3475 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 3476 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 3477 } 3478 3479 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 3480 // Simulate a CAS, to avoid racy duplication of results. 3481 MethodHandle prev = cache[pos]; 3482 if (prev != null) return prev; 3483 return cache[pos] = value; 3484 } 3485 3486 /** 3487 * Provides a target method handle with one or more <em>bound arguments</em> 3488 * in advance of the method handle's invocation. 3489 * The formal parameters to the target corresponding to the bound 3490 * arguments are called <em>bound parameters</em>. 3491 * Returns a new method handle which saves away the bound arguments. 3492 * When it is invoked, it receives arguments for any non-bound parameters, 3493 * binds the saved arguments to their corresponding parameters, 3494 * and calls the original target. 3495 * <p> 3496 * The type of the new method handle will drop the types for the bound 3497 * parameters from the original target type, since the new method handle 3498 * will no longer require those arguments to be supplied by its callers. 3499 * <p> 3500 * Each given argument object must match the corresponding bound parameter type. 3501 * If a bound parameter type is a primitive, the argument object 3502 * must be a wrapper, and will be unboxed to produce the primitive value. 3503 * <p> 3504 * The {@code pos} argument selects which parameters are to be bound. 3505 * It may range between zero and <i>N-L</i> (inclusively), 3506 * where <i>N</i> is the arity of the target method handle 3507 * and <i>L</i> is the length of the values array. 3508 * <p> 3509 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3510 * variable-arity method handle}, even if the original target method handle was. 3511 * @param target the method handle to invoke after the argument is inserted 3512 * @param pos where to insert the argument (zero for the first) 3513 * @param values the series of arguments to insert 3514 * @return a method handle which inserts an additional argument, 3515 * before calling the original method handle 3516 * @throws NullPointerException if the target or the {@code values} array is null 3517 * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than 3518 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 3519 * is the length of the values array. 3520 * @throws ClassCastException if an argument does not match the corresponding bound parameter 3521 * type. 3522 * @see MethodHandle#bindTo 3523 */ 3524 public static 3525 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 3526 int insCount = values.length; 3527 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 3528 if (insCount == 0) return target; 3529 BoundMethodHandle result = target.rebind(); 3530 for (int i = 0; i < insCount; i++) { 3531 Object value = values[i]; 3532 Class<?> ptype = ptypes[pos+i]; 3533 if (ptype.isPrimitive()) { 3534 result = insertArgumentPrimitive(result, pos, ptype, value); 3535 } else { 3536 value = ptype.cast(value); // throw CCE if needed 3537 result = result.bindArgumentL(pos, value); 3538 } 3539 } 3540 return result; 3541 } 3542 3543 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 3544 Class<?> ptype, Object value) { 3545 Wrapper w = Wrapper.forPrimitiveType(ptype); 3546 // perform unboxing and/or primitive conversion 3547 value = w.convert(value, ptype); 3548 switch (w) { 3549 case INT: return result.bindArgumentI(pos, (int)value); 3550 case LONG: return result.bindArgumentJ(pos, (long)value); 3551 case FLOAT: return result.bindArgumentF(pos, (float)value); 3552 case DOUBLE: return result.bindArgumentD(pos, (double)value); 3553 default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 3554 } 3555 } 3556 3557 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 3558 MethodType oldType = target.type(); 3559 int outargs = oldType.parameterCount(); 3560 int inargs = outargs - insCount; 3561 if (inargs < 0) 3562 throw newIllegalArgumentException("too many values to insert"); 3563 if (pos < 0 || pos > inargs) 3564 throw newIllegalArgumentException("no argument type to append"); 3565 return oldType.ptypes(); 3566 } 3567 3568 /** 3569 * Produces a method handle which will discard some dummy arguments 3570 * before calling some other specified <i>target</i> method handle. 3571 * The type of the new method handle will be the same as the target's type, 3572 * except it will also include the dummy argument types, 3573 * at some given position. 3574 * <p> 3575 * The {@code pos} argument may range between zero and <i>N</i>, 3576 * where <i>N</i> is the arity of the target. 3577 * If {@code pos} is zero, the dummy arguments will precede 3578 * the target's real arguments; if {@code pos} is <i>N</i> 3579 * they will come after. 3580 * <p> 3581 * <b>Example:</b> 3582 * <blockquote><pre>{@code 3583 import static java.lang.invoke.MethodHandles.*; 3584 import static java.lang.invoke.MethodType.*; 3585 ... 3586 MethodHandle cat = lookup().findVirtual(String.class, 3587 "concat", methodType(String.class, String.class)); 3588 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3589 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 3590 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 3591 assertEquals(bigType, d0.type()); 3592 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 3593 * }</pre></blockquote> 3594 * <p> 3595 * This method is also equivalent to the following code: 3596 * <blockquote><pre> 3597 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 3598 * </pre></blockquote> 3599 * @param target the method handle to invoke after the arguments are dropped 3600 * @param valueTypes the type(s) of the argument(s) to drop 3601 * @param pos position of first argument to drop (zero for the leftmost) 3602 * @return a method handle which drops arguments of the given types, 3603 * before calling the original method handle 3604 * @throws NullPointerException if the target is null, 3605 * or if the {@code valueTypes} list or any of its elements is null 3606 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3607 * or if {@code pos} is negative or greater than the arity of the target, 3608 * or if the new method handle's type would have too many parameters 3609 */ 3610 public static 3611 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3612 return dropArguments0(target, pos, copyTypes(valueTypes.toArray())); 3613 } 3614 3615 private static List<Class<?>> copyTypes(Object[] array) { 3616 return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class)); 3617 } 3618 3619 private static 3620 MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3621 MethodType oldType = target.type(); // get NPE 3622 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 3623 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 3624 if (dropped == 0) return target; 3625 BoundMethodHandle result = target.rebind(); 3626 LambdaForm lform = result.form; 3627 int insertFormArg = 1 + pos; 3628 for (Class<?> ptype : valueTypes) { 3629 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 3630 } 3631 result = result.copyWith(newType, lform); 3632 return result; 3633 } 3634 3635 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { 3636 int dropped = valueTypes.size(); 3637 MethodType.checkSlotCount(dropped); 3638 int outargs = oldType.parameterCount(); 3639 int inargs = outargs + dropped; 3640 if (pos < 0 || pos > outargs) 3641 throw newIllegalArgumentException("no argument type to remove" 3642 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 3643 ); 3644 return dropped; 3645 } 3646 3647 /** 3648 * Produces a method handle which will discard some dummy arguments 3649 * before calling some other specified <i>target</i> method handle. 3650 * The type of the new method handle will be the same as the target's type, 3651 * except it will also include the dummy argument types, 3652 * at some given position. 3653 * <p> 3654 * The {@code pos} argument may range between zero and <i>N</i>, 3655 * where <i>N</i> is the arity of the target. 3656 * If {@code pos} is zero, the dummy arguments will precede 3657 * the target's real arguments; if {@code pos} is <i>N</i> 3658 * they will come after. 3659 * @apiNote 3660 * <blockquote><pre>{@code 3661 import static java.lang.invoke.MethodHandles.*; 3662 import static java.lang.invoke.MethodType.*; 3663 ... 3664 MethodHandle cat = lookup().findVirtual(String.class, 3665 "concat", methodType(String.class, String.class)); 3666 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3667 MethodHandle d0 = dropArguments(cat, 0, String.class); 3668 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 3669 MethodHandle d1 = dropArguments(cat, 1, String.class); 3670 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 3671 MethodHandle d2 = dropArguments(cat, 2, String.class); 3672 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 3673 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 3674 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 3675 * }</pre></blockquote> 3676 * <p> 3677 * This method is also equivalent to the following code: 3678 * <blockquote><pre> 3679 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 3680 * </pre></blockquote> 3681 * @param target the method handle to invoke after the arguments are dropped 3682 * @param valueTypes the type(s) of the argument(s) to drop 3683 * @param pos position of first argument to drop (zero for the leftmost) 3684 * @return a method handle which drops arguments of the given types, 3685 * before calling the original method handle 3686 * @throws NullPointerException if the target is null, 3687 * or if the {@code valueTypes} array or any of its elements is null 3688 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3689 * or if {@code pos} is negative or greater than the arity of the target, 3690 * or if the new method handle's type would have 3691 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3692 */ 3693 public static 3694 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 3695 return dropArguments0(target, pos, copyTypes(valueTypes)); 3696 } 3697 3698 // private version which allows caller some freedom with error handling 3699 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, 3700 boolean nullOnFailure) { 3701 newTypes = copyTypes(newTypes.toArray()); 3702 List<Class<?>> oldTypes = target.type().parameterList(); 3703 int match = oldTypes.size(); 3704 if (skip != 0) { 3705 if (skip < 0 || skip > match) { 3706 throw newIllegalArgumentException("illegal skip", skip, target); 3707 } 3708 oldTypes = oldTypes.subList(skip, match); 3709 match -= skip; 3710 } 3711 List<Class<?>> addTypes = newTypes; 3712 int add = addTypes.size(); 3713 if (pos != 0) { 3714 if (pos < 0 || pos > add) { 3715 throw newIllegalArgumentException("illegal pos", pos, newTypes); 3716 } 3717 addTypes = addTypes.subList(pos, add); 3718 add -= pos; 3719 assert(addTypes.size() == add); 3720 } 3721 // Do not add types which already match the existing arguments. 3722 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { 3723 if (nullOnFailure) { 3724 return null; 3725 } 3726 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); 3727 } 3728 addTypes = addTypes.subList(match, add); 3729 add -= match; 3730 assert(addTypes.size() == add); 3731 // newTypes: ( P*[pos], M*[match], A*[add] ) 3732 // target: ( S*[skip], M*[match] ) 3733 MethodHandle adapter = target; 3734 if (add > 0) { 3735 adapter = dropArguments0(adapter, skip+ match, addTypes); 3736 } 3737 // adapter: (S*[skip], M*[match], A*[add] ) 3738 if (pos > 0) { 3739 adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos)); 3740 } 3741 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 3742 return adapter; 3743 } 3744 3745 /** 3746 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 3747 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 3748 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 3749 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 3750 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 3751 * {@link #dropArguments(MethodHandle, int, Class[])}. 3752 * <p> 3753 * The resulting handle will have the same return type as the target handle. 3754 * <p> 3755 * In more formal terms, assume these two type lists:<ul> 3756 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 3757 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 3758 * {@code newTypes}. 3759 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 3760 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 3761 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 3762 * sub-list. 3763 * </ul> 3764 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 3765 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 3766 * {@link #dropArguments(MethodHandle, int, Class[])}. 3767 * 3768 * @apiNote 3769 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 3770 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 3771 * <blockquote><pre>{@code 3772 import static java.lang.invoke.MethodHandles.*; 3773 import static java.lang.invoke.MethodType.*; 3774 ... 3775 ... 3776 MethodHandle h0 = constant(boolean.class, true); 3777 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 3778 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 3779 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 3780 if (h1.type().parameterCount() < h2.type().parameterCount()) 3781 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 3782 else 3783 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 3784 MethodHandle h3 = guardWithTest(h0, h1, h2); 3785 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 3786 * }</pre></blockquote> 3787 * @param target the method handle to adapt 3788 * @param skip number of targets parameters to disregard (they will be unchanged) 3789 * @param newTypes the list of types to match {@code target}'s parameter type list to 3790 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 3791 * @return a possibly adapted method handle 3792 * @throws NullPointerException if either argument is null 3793 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 3794 * or if {@code skip} is negative or greater than the arity of the target, 3795 * or if {@code pos} is negative or greater than the newTypes list size, 3796 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 3797 * {@code pos}. 3798 * @since 9 3799 */ 3800 public static 3801 MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 3802 Objects.requireNonNull(target); 3803 Objects.requireNonNull(newTypes); 3804 return dropArgumentsToMatch(target, skip, newTypes, pos, false); 3805 } 3806 3807 /** 3808 * Adapts a target method handle by pre-processing 3809 * one or more of its arguments, each with its own unary filter function, 3810 * and then calling the target with each pre-processed argument 3811 * replaced by the result of its corresponding filter function. 3812 * <p> 3813 * The pre-processing is performed by one or more method handles, 3814 * specified in the elements of the {@code filters} array. 3815 * The first element of the filter array corresponds to the {@code pos} 3816 * argument of the target, and so on in sequence. 3817 * The filter functions are invoked in left to right order. 3818 * <p> 3819 * Null arguments in the array are treated as identity functions, 3820 * and the corresponding arguments left unchanged. 3821 * (If there are no non-null elements in the array, the original target is returned.) 3822 * Each filter is applied to the corresponding argument of the adapter. 3823 * <p> 3824 * If a filter {@code F} applies to the {@code N}th argument of 3825 * the target, then {@code F} must be a method handle which 3826 * takes exactly one argument. The type of {@code F}'s sole argument 3827 * replaces the corresponding argument type of the target 3828 * in the resulting adapted method handle. 3829 * The return type of {@code F} must be identical to the corresponding 3830 * parameter type of the target. 3831 * <p> 3832 * It is an error if there are elements of {@code filters} 3833 * (null or not) 3834 * which do not correspond to argument positions in the target. 3835 * <p><b>Example:</b> 3836 * <blockquote><pre>{@code 3837 import static java.lang.invoke.MethodHandles.*; 3838 import static java.lang.invoke.MethodType.*; 3839 ... 3840 MethodHandle cat = lookup().findVirtual(String.class, 3841 "concat", methodType(String.class, String.class)); 3842 MethodHandle upcase = lookup().findVirtual(String.class, 3843 "toUpperCase", methodType(String.class)); 3844 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3845 MethodHandle f0 = filterArguments(cat, 0, upcase); 3846 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 3847 MethodHandle f1 = filterArguments(cat, 1, upcase); 3848 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 3849 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 3850 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 3851 * }</pre></blockquote> 3852 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3853 * denotes the return type of both the {@code target} and resulting adapter. 3854 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 3855 * of the parameters and arguments that precede and follow the filter position 3856 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 3857 * values of the filtered parameters and arguments; they also represent the 3858 * return types of the {@code filter[i]} handles. The latter accept arguments 3859 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 3860 * the resulting adapter. 3861 * <blockquote><pre>{@code 3862 * T target(P... p, A[i]... a[i], B... b); 3863 * A[i] filter[i](V[i]); 3864 * T adapter(P... p, V[i]... v[i], B... b) { 3865 * return target(p..., filter[i](v[i])..., b...); 3866 * } 3867 * }</pre></blockquote> 3868 * <p> 3869 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3870 * variable-arity method handle}, even if the original target method handle was. 3871 * 3872 * @param target the method handle to invoke after arguments are filtered 3873 * @param pos the position of the first argument to filter 3874 * @param filters method handles to call initially on filtered arguments 3875 * @return method handle which incorporates the specified argument filtering logic 3876 * @throws NullPointerException if the target is null 3877 * or if the {@code filters} array is null 3878 * @throws IllegalArgumentException if a non-null element of {@code filters} 3879 * does not match a corresponding argument type of target as described above, 3880 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 3881 * or if the resulting method handle's type would have 3882 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3883 */ 3884 public static 3885 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 3886 // In method types arguments start at index 0, while the LF 3887 // editor have the MH receiver at position 0 - adjust appropriately. 3888 final int MH_RECEIVER_OFFSET = 1; 3889 filterArgumentsCheckArity(target, pos, filters); 3890 MethodHandle adapter = target; 3891 3892 // keep track of currently matched filters, as to optimize repeated filters 3893 int index = 0; 3894 int[] positions = new int[filters.length]; 3895 MethodHandle filter = null; 3896 3897 // process filters in reverse order so that the invocation of 3898 // the resulting adapter will invoke the filters in left-to-right order 3899 for (int i = filters.length - 1; i >= 0; --i) { 3900 MethodHandle newFilter = filters[i]; 3901 if (newFilter == null) continue; // ignore null elements of filters 3902 3903 // flush changes on update 3904 if (filter != newFilter) { 3905 if (filter != null) { 3906 if (index > 1) { 3907 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 3908 } else { 3909 adapter = filterArgument(adapter, positions[0] - 1, filter); 3910 } 3911 } 3912 filter = newFilter; 3913 index = 0; 3914 } 3915 3916 filterArgumentChecks(target, pos + i, newFilter); 3917 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 3918 } 3919 if (index > 1) { 3920 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 3921 } else if (index == 1) { 3922 adapter = filterArgument(adapter, positions[0] - 1, filter); 3923 } 3924 return adapter; 3925 } 3926 3927 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 3928 MethodType targetType = adapter.type(); 3929 MethodType filterType = filter.type(); 3930 BoundMethodHandle result = adapter.rebind(); 3931 Class<?> newParamType = filterType.parameterType(0); 3932 3933 Class<?>[] ptypes = targetType.ptypes().clone(); 3934 for (int pos : positions) { 3935 ptypes[pos - 1] = newParamType; 3936 } 3937 MethodType newType = MethodType.makeImpl(targetType.rtype(), ptypes, true); 3938 3939 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 3940 return result.copyWithExtendL(newType, lform, filter); 3941 } 3942 3943 /*non-public*/ static 3944 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 3945 filterArgumentChecks(target, pos, filter); 3946 MethodType targetType = target.type(); 3947 MethodType filterType = filter.type(); 3948 BoundMethodHandle result = target.rebind(); 3949 Class<?> newParamType = filterType.parameterType(0); 3950 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 3951 MethodType newType = targetType.changeParameterType(pos, newParamType); 3952 result = result.copyWithExtendL(newType, lform, filter); 3953 return result; 3954 } 3955 3956 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 3957 MethodType targetType = target.type(); 3958 int maxPos = targetType.parameterCount(); 3959 if (pos + filters.length > maxPos) 3960 throw newIllegalArgumentException("too many filters"); 3961 } 3962 3963 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3964 MethodType targetType = target.type(); 3965 MethodType filterType = filter.type(); 3966 if (filterType.parameterCount() != 1 3967 || filterType.returnType() != targetType.parameterType(pos)) 3968 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3969 } 3970 3971 /** 3972 * Adapts a target method handle by pre-processing 3973 * a sub-sequence of its arguments with a filter (another method handle). 3974 * The pre-processed arguments are replaced by the result (if any) of the 3975 * filter function. 3976 * The target is then called on the modified (usually shortened) argument list. 3977 * <p> 3978 * If the filter returns a value, the target must accept that value as 3979 * its argument in position {@code pos}, preceded and/or followed by 3980 * any arguments not passed to the filter. 3981 * If the filter returns void, the target must accept all arguments 3982 * not passed to the filter. 3983 * No arguments are reordered, and a result returned from the filter 3984 * replaces (in order) the whole subsequence of arguments originally 3985 * passed to the adapter. 3986 * <p> 3987 * The argument types (if any) of the filter 3988 * replace zero or one argument types of the target, at position {@code pos}, 3989 * in the resulting adapted method handle. 3990 * The return type of the filter (if any) must be identical to the 3991 * argument type of the target at position {@code pos}, and that target argument 3992 * is supplied by the return value of the filter. 3993 * <p> 3994 * In all cases, {@code pos} must be greater than or equal to zero, and 3995 * {@code pos} must also be less than or equal to the target's arity. 3996 * <p><b>Example:</b> 3997 * <blockquote><pre>{@code 3998 import static java.lang.invoke.MethodHandles.*; 3999 import static java.lang.invoke.MethodType.*; 4000 ... 4001 MethodHandle deepToString = publicLookup() 4002 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 4003 4004 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 4005 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 4006 4007 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 4008 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 4009 4010 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 4011 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 4012 assertEquals("[top, [up, down], strange]", 4013 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 4014 4015 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 4016 assertEquals("[top, [up, down], [strange]]", 4017 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 4018 4019 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 4020 assertEquals("[top, [[up, down, strange], charm], bottom]", 4021 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 4022 * }</pre></blockquote> 4023 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 4024 * represents the return type of the {@code target} and resulting adapter. 4025 * {@code V}/{@code v} stand for the return type and value of the 4026 * {@code filter}, which are also found in the signature and arguments of 4027 * the {@code target}, respectively, unless {@code V} is {@code void}. 4028 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 4029 * and values preceding and following the collection position, {@code pos}, 4030 * in the {@code target}'s signature. They also turn up in the resulting 4031 * adapter's signature and arguments, where they surround 4032 * {@code B}/{@code b}, which represent the parameter types and arguments 4033 * to the {@code filter} (if any). 4034 * <blockquote><pre>{@code 4035 * T target(A...,V,C...); 4036 * V filter(B...); 4037 * T adapter(A... a,B... b,C... c) { 4038 * V v = filter(b...); 4039 * return target(a...,v,c...); 4040 * } 4041 * // and if the filter has no arguments: 4042 * T target2(A...,V,C...); 4043 * V filter2(); 4044 * T adapter2(A... a,C... c) { 4045 * V v = filter2(); 4046 * return target2(a...,v,c...); 4047 * } 4048 * // and if the filter has a void return: 4049 * T target3(A...,C...); 4050 * void filter3(B...); 4051 * T adapter3(A... a,B... b,C... c) { 4052 * filter3(b...); 4053 * return target3(a...,c...); 4054 * } 4055 * }</pre></blockquote> 4056 * <p> 4057 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 4058 * one which first "folds" the affected arguments, and then drops them, in separate 4059 * steps as follows: 4060 * <blockquote><pre>{@code 4061 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 4062 * mh = MethodHandles.foldArguments(mh, coll); //step 1 4063 * }</pre></blockquote> 4064 * If the target method handle consumes no arguments besides than the result 4065 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 4066 * is equivalent to {@code filterReturnValue(coll, mh)}. 4067 * If the filter method handle {@code coll} consumes one argument and produces 4068 * a non-void result, then {@code collectArguments(mh, N, coll)} 4069 * is equivalent to {@code filterArguments(mh, N, coll)}. 4070 * Other equivalences are possible but would require argument permutation. 4071 * <p> 4072 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4073 * variable-arity method handle}, even if the original target method handle was. 4074 * 4075 * @param target the method handle to invoke after filtering the subsequence of arguments 4076 * @param pos the position of the first adapter argument to pass to the filter, 4077 * and/or the target argument which receives the result of the filter 4078 * @param filter method handle to call on the subsequence of arguments 4079 * @return method handle which incorporates the specified argument subsequence filtering logic 4080 * @throws NullPointerException if either argument is null 4081 * @throws IllegalArgumentException if the return type of {@code filter} 4082 * is non-void and is not the same as the {@code pos} argument of the target, 4083 * or if {@code pos} is not between 0 and the target's arity, inclusive, 4084 * or if the resulting method handle's type would have 4085 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4086 * @see MethodHandles#foldArguments 4087 * @see MethodHandles#filterArguments 4088 * @see MethodHandles#filterReturnValue 4089 */ 4090 public static 4091 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 4092 MethodType newType = collectArgumentsChecks(target, pos, filter); 4093 MethodType collectorType = filter.type(); 4094 BoundMethodHandle result = target.rebind(); 4095 LambdaForm lform; 4096 if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { 4097 lform = result.editor().collectArgumentArrayForm(1 + pos, filter); 4098 if (lform != null) { 4099 return result.copyWith(newType, lform); 4100 } 4101 } 4102 lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 4103 return result.copyWithExtendL(newType, lform, filter); 4104 } 4105 4106 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 4107 MethodType targetType = target.type(); 4108 MethodType filterType = filter.type(); 4109 Class<?> rtype = filterType.returnType(); 4110 List<Class<?>> filterArgs = filterType.parameterList(); 4111 if (rtype == void.class) { 4112 return targetType.insertParameterTypes(pos, filterArgs); 4113 } 4114 if (rtype != targetType.parameterType(pos)) { 4115 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 4116 } 4117 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); 4118 } 4119 4120 /** 4121 * Adapts a target method handle by post-processing 4122 * its return value (if any) with a filter (another method handle). 4123 * The result of the filter is returned from the adapter. 4124 * <p> 4125 * If the target returns a value, the filter must accept that value as 4126 * its only argument. 4127 * If the target returns void, the filter must accept no arguments. 4128 * <p> 4129 * The return type of the filter 4130 * replaces the return type of the target 4131 * in the resulting adapted method handle. 4132 * The argument type of the filter (if any) must be identical to the 4133 * return type of the target. 4134 * <p><b>Example:</b> 4135 * <blockquote><pre>{@code 4136 import static java.lang.invoke.MethodHandles.*; 4137 import static java.lang.invoke.MethodType.*; 4138 ... 4139 MethodHandle cat = lookup().findVirtual(String.class, 4140 "concat", methodType(String.class, String.class)); 4141 MethodHandle length = lookup().findVirtual(String.class, 4142 "length", methodType(int.class)); 4143 System.out.println((String) cat.invokeExact("x", "y")); // xy 4144 MethodHandle f0 = filterReturnValue(cat, length); 4145 System.out.println((int) f0.invokeExact("x", "y")); // 2 4146 * }</pre></blockquote> 4147 * <p>Here is pseudocode for the resulting adapter. In the code, 4148 * {@code T}/{@code t} represent the result type and value of the 4149 * {@code target}; {@code V}, the result type of the {@code filter}; and 4150 * {@code A}/{@code a}, the types and values of the parameters and arguments 4151 * of the {@code target} as well as the resulting adapter. 4152 * <blockquote><pre>{@code 4153 * T target(A...); 4154 * V filter(T); 4155 * V adapter(A... a) { 4156 * T t = target(a...); 4157 * return filter(t); 4158 * } 4159 * // and if the target has a void return: 4160 * void target2(A...); 4161 * V filter2(); 4162 * V adapter2(A... a) { 4163 * target2(a...); 4164 * return filter2(); 4165 * } 4166 * // and if the filter has a void return: 4167 * T target3(A...); 4168 * void filter3(V); 4169 * void adapter3(A... a) { 4170 * T t = target3(a...); 4171 * filter3(t); 4172 * } 4173 * }</pre></blockquote> 4174 * <p> 4175 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4176 * variable-arity method handle}, even if the original target method handle was. 4177 * @param target the method handle to invoke before filtering the return value 4178 * @param filter method handle to call on the return value 4179 * @return method handle which incorporates the specified return value filtering logic 4180 * @throws NullPointerException if either argument is null 4181 * @throws IllegalArgumentException if the argument list of {@code filter} 4182 * does not match the return type of target as described above 4183 */ 4184 public static 4185 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 4186 MethodType targetType = target.type(); 4187 MethodType filterType = filter.type(); 4188 filterReturnValueChecks(targetType, filterType); 4189 BoundMethodHandle result = target.rebind(); 4190 BasicType rtype = BasicType.basicType(filterType.returnType()); 4191 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 4192 MethodType newType = targetType.changeReturnType(filterType.returnType()); 4193 result = result.copyWithExtendL(newType, lform, filter); 4194 return result; 4195 } 4196 4197 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 4198 Class<?> rtype = targetType.returnType(); 4199 int filterValues = filterType.parameterCount(); 4200 if (filterValues == 0 4201 ? (rtype != void.class) 4202 : (rtype != filterType.parameterType(0) || filterValues != 1)) 4203 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 4204 } 4205 4206 /** 4207 * Adapts a target method handle by pre-processing 4208 * some of its arguments, and then calling the target with 4209 * the result of the pre-processing, inserted into the original 4210 * sequence of arguments. 4211 * <p> 4212 * The pre-processing is performed by {@code combiner}, a second method handle. 4213 * Of the arguments passed to the adapter, the first {@code N} arguments 4214 * are copied to the combiner, which is then called. 4215 * (Here, {@code N} is defined as the parameter count of the combiner.) 4216 * After this, control passes to the target, with any result 4217 * from the combiner inserted before the original {@code N} incoming 4218 * arguments. 4219 * <p> 4220 * If the combiner returns a value, the first parameter type of the target 4221 * must be identical with the return type of the combiner, and the next 4222 * {@code N} parameter types of the target must exactly match the parameters 4223 * of the combiner. 4224 * <p> 4225 * If the combiner has a void return, no result will be inserted, 4226 * and the first {@code N} parameter types of the target 4227 * must exactly match the parameters of the combiner. 4228 * <p> 4229 * The resulting adapter is the same type as the target, except that the 4230 * first parameter type is dropped, 4231 * if it corresponds to the result of the combiner. 4232 * <p> 4233 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 4234 * that either the combiner or the target does not wish to receive. 4235 * If some of the incoming arguments are destined only for the combiner, 4236 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 4237 * arguments will not need to be live on the stack on entry to the 4238 * target.) 4239 * <p><b>Example:</b> 4240 * <blockquote><pre>{@code 4241 import static java.lang.invoke.MethodHandles.*; 4242 import static java.lang.invoke.MethodType.*; 4243 ... 4244 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 4245 "println", methodType(void.class, String.class)) 4246 .bindTo(System.out); 4247 MethodHandle cat = lookup().findVirtual(String.class, 4248 "concat", methodType(String.class, String.class)); 4249 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 4250 MethodHandle catTrace = foldArguments(cat, trace); 4251 // also prints "boo": 4252 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 4253 * }</pre></blockquote> 4254 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 4255 * represents the result type of the {@code target} and resulting adapter. 4256 * {@code V}/{@code v} represent the type and value of the parameter and argument 4257 * of {@code target} that precedes the folding position; {@code V} also is 4258 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 4259 * types and values of the {@code N} parameters and arguments at the folding 4260 * position. {@code B}/{@code b} represent the types and values of the 4261 * {@code target} parameters and arguments that follow the folded parameters 4262 * and arguments. 4263 * <blockquote><pre>{@code 4264 * // there are N arguments in A... 4265 * T target(V, A[N]..., B...); 4266 * V combiner(A...); 4267 * T adapter(A... a, B... b) { 4268 * V v = combiner(a...); 4269 * return target(v, a..., b...); 4270 * } 4271 * // and if the combiner has a void return: 4272 * T target2(A[N]..., B...); 4273 * void combiner2(A...); 4274 * T adapter2(A... a, B... b) { 4275 * combiner2(a...); 4276 * return target2(a..., b...); 4277 * } 4278 * }</pre></blockquote> 4279 * <p> 4280 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4281 * variable-arity method handle}, even if the original target method handle was. 4282 * @param target the method handle to invoke after arguments are combined 4283 * @param combiner method handle to call initially on the incoming arguments 4284 * @return method handle which incorporates the specified argument folding logic 4285 * @throws NullPointerException if either argument is null 4286 * @throws IllegalArgumentException if {@code combiner}'s return type 4287 * is non-void and not the same as the first argument type of 4288 * the target, or if the initial {@code N} argument types 4289 * of the target 4290 * (skipping one matching the {@code combiner}'s return type) 4291 * are not identical with the argument types of {@code combiner} 4292 */ 4293 public static 4294 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 4295 return foldArguments(target, 0, combiner); 4296 } 4297 4298 /** 4299 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 4300 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 4301 * before the folded arguments. 4302 * <p> 4303 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 4304 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 4305 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 4306 * 0. 4307 * 4308 * @apiNote Example: 4309 * <blockquote><pre>{@code 4310 import static java.lang.invoke.MethodHandles.*; 4311 import static java.lang.invoke.MethodType.*; 4312 ... 4313 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 4314 "println", methodType(void.class, String.class)) 4315 .bindTo(System.out); 4316 MethodHandle cat = lookup().findVirtual(String.class, 4317 "concat", methodType(String.class, String.class)); 4318 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 4319 MethodHandle catTrace = foldArguments(cat, 1, trace); 4320 // also prints "jum": 4321 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 4322 * }</pre></blockquote> 4323 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 4324 * represents the result type of the {@code target} and resulting adapter. 4325 * {@code V}/{@code v} represent the type and value of the parameter and argument 4326 * of {@code target} that precedes the folding position; {@code V} also is 4327 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 4328 * types and values of the {@code N} parameters and arguments at the folding 4329 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 4330 * and values of the {@code target} parameters and arguments that precede and 4331 * follow the folded parameters and arguments starting at {@code pos}, 4332 * respectively. 4333 * <blockquote><pre>{@code 4334 * // there are N arguments in A... 4335 * T target(Z..., V, A[N]..., B...); 4336 * V combiner(A...); 4337 * T adapter(Z... z, A... a, B... b) { 4338 * V v = combiner(a...); 4339 * return target(z..., v, a..., b...); 4340 * } 4341 * // and if the combiner has a void return: 4342 * T target2(Z..., A[N]..., B...); 4343 * void combiner2(A...); 4344 * T adapter2(Z... z, A... a, B... b) { 4345 * combiner2(a...); 4346 * return target2(z..., a..., b...); 4347 * } 4348 * }</pre></blockquote> 4349 * <p> 4350 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4351 * variable-arity method handle}, even if the original target method handle was. 4352 * 4353 * @param target the method handle to invoke after arguments are combined 4354 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 4355 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 4356 * @param combiner method handle to call initially on the incoming arguments 4357 * @return method handle which incorporates the specified argument folding logic 4358 * @throws NullPointerException if either argument is null 4359 * @throws IllegalArgumentException if either of the following two conditions holds: 4360 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 4361 * {@code pos} of the target signature; 4362 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 4363 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 4364 * 4365 * @see #foldArguments(MethodHandle, MethodHandle) 4366 * @since 9 4367 */ 4368 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 4369 MethodType targetType = target.type(); 4370 MethodType combinerType = combiner.type(); 4371 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 4372 BoundMethodHandle result = target.rebind(); 4373 boolean dropResult = rtype == void.class; 4374 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 4375 MethodType newType = targetType; 4376 if (!dropResult) { 4377 newType = newType.dropParameterTypes(pos, pos + 1); 4378 } 4379 result = result.copyWithExtendL(newType, lform, combiner); 4380 return result; 4381 } 4382 4383 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 4384 int foldArgs = combinerType.parameterCount(); 4385 Class<?> rtype = combinerType.returnType(); 4386 int foldVals = rtype == void.class ? 0 : 1; 4387 int afterInsertPos = foldPos + foldVals; 4388 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 4389 if (ok) { 4390 for (int i = 0; i < foldArgs; i++) { 4391 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 4392 ok = false; 4393 break; 4394 } 4395 } 4396 } 4397 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 4398 ok = false; 4399 if (!ok) 4400 throw misMatchedTypes("target and combiner types", targetType, combinerType); 4401 return rtype; 4402 } 4403 4404 /** 4405 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 4406 * of the pre-processing replacing the argument at the given position. 4407 * 4408 * @param target the method handle to invoke after arguments are combined 4409 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 4410 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 4411 * @param combiner method handle to call initially on the incoming arguments 4412 * @param argPositions indexes of the target to pick arguments sent to the combiner from 4413 * @return method handle which incorporates the specified argument folding logic 4414 * @throws NullPointerException if either argument is null 4415 * @throws IllegalArgumentException if either of the following two conditions holds: 4416 * (1) {@code combiner}'s return type is not the same as the argument type at position 4417 * {@code pos} of the target signature; 4418 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 4419 * not identical with the argument types of {@code combiner}. 4420 */ 4421 /*non-public*/ static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 4422 return argumentsWithCombiner(true, target, position, combiner, argPositions); 4423 } 4424 4425 /** 4426 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 4427 * the pre-processing inserted into the original sequence of arguments at the given position. 4428 * 4429 * @param target the method handle to invoke after arguments are combined 4430 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 4431 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 4432 * @param combiner method handle to call initially on the incoming arguments 4433 * @param argPositions indexes of the target to pick arguments sent to the combiner from 4434 * @return method handle which incorporates the specified argument folding logic 4435 * @throws NullPointerException if either argument is null 4436 * @throws IllegalArgumentException if either of the following two conditions holds: 4437 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 4438 * {@code pos} of the target signature; 4439 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 4440 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 4441 * with the argument types of {@code combiner}. 4442 */ 4443 /*non-public*/ static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 4444 return argumentsWithCombiner(false, target, position, combiner, argPositions); 4445 } 4446 4447 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 4448 MethodType targetType = target.type(); 4449 MethodType combinerType = combiner.type(); 4450 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 4451 BoundMethodHandle result = target.rebind(); 4452 4453 MethodType newType = targetType; 4454 LambdaForm lform; 4455 if (filter) { 4456 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 4457 } else { 4458 boolean dropResult = rtype == void.class; 4459 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 4460 if (!dropResult) { 4461 newType = newType.dropParameterTypes(position, position + 1); 4462 } 4463 } 4464 result = result.copyWithExtendL(newType, lform, combiner); 4465 return result; 4466 } 4467 4468 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 4469 int combinerArgs = combinerType.parameterCount(); 4470 if (argPos.length != combinerArgs) { 4471 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 4472 } 4473 Class<?> rtype = combinerType.returnType(); 4474 4475 for (int i = 0; i < combinerArgs; i++) { 4476 int arg = argPos[i]; 4477 if (arg < 0 || arg > targetType.parameterCount()) { 4478 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 4479 } 4480 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 4481 throw newIllegalArgumentException("target argument type at position " + arg 4482 + " must match combiner argument type at index " + i + ": " + targetType 4483 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 4484 } 4485 } 4486 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 4487 throw misMatchedTypes("target and combiner types", targetType, combinerType); 4488 } 4489 return rtype; 4490 } 4491 4492 /** 4493 * Makes a method handle which adapts a target method handle, 4494 * by guarding it with a test, a boolean-valued method handle. 4495 * If the guard fails, a fallback handle is called instead. 4496 * All three method handles must have the same corresponding 4497 * argument and return types, except that the return type 4498 * of the test must be boolean, and the test is allowed 4499 * to have fewer arguments than the other two method handles. 4500 * <p> 4501 * Here is pseudocode for the resulting adapter. In the code, {@code T} 4502 * represents the uniform result type of the three involved handles; 4503 * {@code A}/{@code a}, the types and values of the {@code target} 4504 * parameters and arguments that are consumed by the {@code test}; and 4505 * {@code B}/{@code b}, those types and values of the {@code target} 4506 * parameters and arguments that are not consumed by the {@code test}. 4507 * <blockquote><pre>{@code 4508 * boolean test(A...); 4509 * T target(A...,B...); 4510 * T fallback(A...,B...); 4511 * T adapter(A... a,B... b) { 4512 * if (test(a...)) 4513 * return target(a..., b...); 4514 * else 4515 * return fallback(a..., b...); 4516 * } 4517 * }</pre></blockquote> 4518 * Note that the test arguments ({@code a...} in the pseudocode) cannot 4519 * be modified by execution of the test, and so are passed unchanged 4520 * from the caller to the target or fallback as appropriate. 4521 * @param test method handle used for test, must return boolean 4522 * @param target method handle to call if test passes 4523 * @param fallback method handle to call if test fails 4524 * @return method handle which incorporates the specified if/then/else logic 4525 * @throws NullPointerException if any argument is null 4526 * @throws IllegalArgumentException if {@code test} does not return boolean, 4527 * or if all three method types do not match (with the return 4528 * type of {@code test} changed to match that of the target). 4529 */ 4530 public static 4531 MethodHandle guardWithTest(MethodHandle test, 4532 MethodHandle target, 4533 MethodHandle fallback) { 4534 MethodType gtype = test.type(); 4535 MethodType ttype = target.type(); 4536 MethodType ftype = fallback.type(); 4537 if (!ttype.equals(ftype)) 4538 throw misMatchedTypes("target and fallback types", ttype, ftype); 4539 if (gtype.returnType() != boolean.class) 4540 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 4541 List<Class<?>> targs = ttype.parameterList(); 4542 test = dropArgumentsToMatch(test, 0, targs, 0, true); 4543 if (test == null) { 4544 throw misMatchedTypes("target and test types", ttype, gtype); 4545 } 4546 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 4547 } 4548 4549 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 4550 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 4551 } 4552 4553 /** 4554 * Makes a method handle which adapts a target method handle, 4555 * by running it inside an exception handler. 4556 * If the target returns normally, the adapter returns that value. 4557 * If an exception matching the specified type is thrown, the fallback 4558 * handle is called instead on the exception, plus the original arguments. 4559 * <p> 4560 * The target and handler must have the same corresponding 4561 * argument and return types, except that handler may omit trailing arguments 4562 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 4563 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 4564 * <p> 4565 * Here is pseudocode for the resulting adapter. In the code, {@code T} 4566 * represents the return type of the {@code target} and {@code handler}, 4567 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 4568 * the types and values of arguments to the resulting handle consumed by 4569 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 4570 * resulting handle discarded by {@code handler}. 4571 * <blockquote><pre>{@code 4572 * T target(A..., B...); 4573 * T handler(ExType, A...); 4574 * T adapter(A... a, B... b) { 4575 * try { 4576 * return target(a..., b...); 4577 * } catch (ExType ex) { 4578 * return handler(ex, a...); 4579 * } 4580 * } 4581 * }</pre></blockquote> 4582 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 4583 * be modified by execution of the target, and so are passed unchanged 4584 * from the caller to the handler, if the handler is invoked. 4585 * <p> 4586 * The target and handler must return the same type, even if the handler 4587 * always throws. (This might happen, for instance, because the handler 4588 * is simulating a {@code finally} clause). 4589 * To create such a throwing handler, compose the handler creation logic 4590 * with {@link #throwException throwException}, 4591 * in order to create a method handle of the correct return type. 4592 * @param target method handle to call 4593 * @param exType the type of exception which the handler will catch 4594 * @param handler method handle to call if a matching exception is thrown 4595 * @return method handle which incorporates the specified try/catch logic 4596 * @throws NullPointerException if any argument is null 4597 * @throws IllegalArgumentException if {@code handler} does not accept 4598 * the given exception type, or if the method handle types do 4599 * not match in their return types and their 4600 * corresponding parameters 4601 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 4602 */ 4603 public static 4604 MethodHandle catchException(MethodHandle target, 4605 Class<? extends Throwable> exType, 4606 MethodHandle handler) { 4607 MethodType ttype = target.type(); 4608 MethodType htype = handler.type(); 4609 if (!Throwable.class.isAssignableFrom(exType)) 4610 throw new ClassCastException(exType.getName()); 4611 if (htype.parameterCount() < 1 || 4612 !htype.parameterType(0).isAssignableFrom(exType)) 4613 throw newIllegalArgumentException("handler does not accept exception type "+exType); 4614 if (htype.returnType() != ttype.returnType()) 4615 throw misMatchedTypes("target and handler return types", ttype, htype); 4616 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); 4617 if (handler == null) { 4618 throw misMatchedTypes("target and handler types", ttype, htype); 4619 } 4620 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 4621 } 4622 4623 /** 4624 * Produces a method handle which will throw exceptions of the given {@code exType}. 4625 * The method handle will accept a single argument of {@code exType}, 4626 * and immediately throw it as an exception. 4627 * The method type will nominally specify a return of {@code returnType}. 4628 * The return type may be anything convenient: It doesn't matter to the 4629 * method handle's behavior, since it will never return normally. 4630 * @param returnType the return type of the desired method handle 4631 * @param exType the parameter type of the desired method handle 4632 * @return method handle which can throw the given exceptions 4633 * @throws NullPointerException if either argument is null 4634 */ 4635 public static 4636 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 4637 if (!Throwable.class.isAssignableFrom(exType)) 4638 throw new ClassCastException(exType.getName()); 4639 return MethodHandleImpl.throwException(methodType(returnType, exType)); 4640 } 4641 4642 /** 4643 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 4644 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 4645 * delivers the loop's result, which is the return value of the resulting handle. 4646 * <p> 4647 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 4648 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 4649 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 4650 * terms of method handles, each clause will specify up to four independent actions:<ul> 4651 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 4652 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 4653 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 4654 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 4655 * </ul> 4656 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 4657 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 4658 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 4659 * <p> 4660 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 4661 * this case. See below for a detailed description. 4662 * <p> 4663 * <em>Parameters optional everywhere:</em> 4664 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 4665 * As an exception, the init functions cannot take any {@code v} parameters, 4666 * because those values are not yet computed when the init functions are executed. 4667 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 4668 * In fact, any clause function may take no arguments at all. 4669 * <p> 4670 * <em>Loop parameters:</em> 4671 * A clause function may take all the iteration variable values it is entitled to, in which case 4672 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 4673 * with their types and values notated as {@code (A...)} and {@code (a...)}. 4674 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 4675 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 4676 * init function is automatically a loop parameter {@code a}.) 4677 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 4678 * These loop parameters act as loop-invariant values visible across the whole loop. 4679 * <p> 4680 * <em>Parameters visible everywhere:</em> 4681 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 4682 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 4683 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 4684 * Most clause functions will not need all of this information, but they will be formally connected to it 4685 * as if by {@link #dropArguments}. 4686 * <a id="astar"></a> 4687 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 4688 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 4689 * In that notation, the general form of an init function parameter list 4690 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 4691 * <p> 4692 * <em>Checking clause structure:</em> 4693 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 4694 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 4695 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 4696 * met by the inputs to the loop combinator. 4697 * <p> 4698 * <em>Effectively identical sequences:</em> 4699 * <a id="effid"></a> 4700 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 4701 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 4702 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 4703 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 4704 * that longest list. 4705 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 4706 * and the same is true if more sequences of the form {@code (V... A*)} are added. 4707 * <p> 4708 * <em>Step 0: Determine clause structure.</em><ol type="a"> 4709 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 4710 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 4711 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 4712 * four. Padding takes place by appending elements to the array. 4713 * <li>Clauses with all {@code null}s are disregarded. 4714 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 4715 * </ol> 4716 * <p> 4717 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 4718 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 4719 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 4720 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 4721 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 4722 * iteration variable type. 4723 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 4724 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 4725 * </ol> 4726 * <p> 4727 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 4728 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 4729 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 4730 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 4731 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 4732 * (These types will be checked in step 2, along with all the clause function types.) 4733 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 4734 * <li>All of the collected parameter lists must be effectively identical. 4735 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 4736 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 4737 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 4738 * the "internal parameter list". 4739 * </ul> 4740 * <p> 4741 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 4742 * <li>Examine fini function return types, disregarding omitted fini functions. 4743 * <li>If there are no fini functions, the loop return type is {@code void}. 4744 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 4745 * type. 4746 * </ol> 4747 * <p> 4748 * <em>Step 1D: Check other types.</em><ol type="a"> 4749 * <li>There must be at least one non-omitted pred function. 4750 * <li>Every non-omitted pred function must have a {@code boolean} return type. 4751 * </ol> 4752 * <p> 4753 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 4754 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 4755 * <li>The parameter list for init functions will be adjusted to the external parameter list. 4756 * (Note that their parameter lists are already effectively identical to this list.) 4757 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 4758 * effectively identical to the internal parameter list {@code (V... A...)}. 4759 * </ol> 4760 * <p> 4761 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 4762 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 4763 * type. 4764 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 4765 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 4766 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 4767 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 4768 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 4769 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 4770 * loop return type. 4771 * </ol> 4772 * <p> 4773 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 4774 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 4775 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 4776 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 4777 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 4778 * pad out the end of the list. 4779 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 4780 * </ol> 4781 * <p> 4782 * <em>Final observations.</em><ol type="a"> 4783 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 4784 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 4785 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 4786 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 4787 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 4788 * <li>Each pair of init and step functions agrees in their return type {@code V}. 4789 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 4790 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 4791 * </ol> 4792 * <p> 4793 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 4794 * <ul> 4795 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 4796 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 4797 * (Only one {@code Pn} has to be non-{@code null}.) 4798 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 4799 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 4800 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 4801 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 4802 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 4803 * the resulting loop handle's parameter types {@code (A...)}. 4804 * </ul> 4805 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 4806 * which is natural if most of the loop computation happens in the steps. For some loops, 4807 * the burden of computation might be heaviest in the pred functions, and so the pred functions 4808 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 4809 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 4810 * where the init functions will need the extra parameters. For such reasons, the rules for 4811 * determining these parameters are as symmetric as possible, across all clause parts. 4812 * In general, the loop parameters function as common invariant values across the whole 4813 * loop, while the iteration variables function as common variant values, or (if there is 4814 * no step function) as internal loop invariant temporaries. 4815 * <p> 4816 * <em>Loop execution.</em><ol type="a"> 4817 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 4818 * every clause function. These locals are loop invariant. 4819 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 4820 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 4821 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 4822 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 4823 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 4824 * (in argument order). 4825 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 4826 * returns {@code false}. 4827 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 4828 * sequence {@code (v...)} of loop variables. 4829 * The updated value is immediately visible to all subsequent function calls. 4830 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 4831 * (of type {@code R}) is returned from the loop as a whole. 4832 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 4833 * except by throwing an exception. 4834 * </ol> 4835 * <p> 4836 * <em>Usage tips.</em> 4837 * <ul> 4838 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 4839 * sometimes a step function only needs to observe the current value of its own variable. 4840 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 4841 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 4842 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 4843 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 4844 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 4845 * <li>If some of the clause functions are virtual methods on an instance, the instance 4846 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 4847 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 4848 * will be the first iteration variable value, and it will be easy to use virtual 4849 * methods as clause parts, since all of them will take a leading instance reference matching that value. 4850 * </ul> 4851 * <p> 4852 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 4853 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 4854 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 4855 * <blockquote><pre>{@code 4856 * V... init...(A...); 4857 * boolean pred...(V..., A...); 4858 * V... step...(V..., A...); 4859 * R fini...(V..., A...); 4860 * R loop(A... a) { 4861 * V... v... = init...(a...); 4862 * for (;;) { 4863 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 4864 * v = s(v..., a...); 4865 * if (!p(v..., a...)) { 4866 * return f(v..., a...); 4867 * } 4868 * } 4869 * } 4870 * } 4871 * }</pre></blockquote> 4872 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 4873 * to their full length, even though individual clause functions may neglect to take them all. 4874 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 4875 * 4876 * @apiNote Example: 4877 * <blockquote><pre>{@code 4878 * // iterative implementation of the factorial function as a loop handle 4879 * static int one(int k) { return 1; } 4880 * static int inc(int i, int acc, int k) { return i + 1; } 4881 * static int mult(int i, int acc, int k) { return i * acc; } 4882 * static boolean pred(int i, int acc, int k) { return i < k; } 4883 * static int fin(int i, int acc, int k) { return acc; } 4884 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4885 * // null initializer for counter, should initialize to 0 4886 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4887 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4888 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4889 * assertEquals(120, loop.invoke(5)); 4890 * }</pre></blockquote> 4891 * The same example, dropping arguments and using combinators: 4892 * <blockquote><pre>{@code 4893 * // simplified implementation of the factorial function as a loop handle 4894 * static int inc(int i) { return i + 1; } // drop acc, k 4895 * static int mult(int i, int acc) { return i * acc; } //drop k 4896 * static boolean cmp(int i, int k) { return i < k; } 4897 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 4898 * // null initializer for counter, should initialize to 0 4899 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 4900 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 4901 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 4902 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4903 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4904 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4905 * assertEquals(720, loop.invoke(6)); 4906 * }</pre></blockquote> 4907 * A similar example, using a helper object to hold a loop parameter: 4908 * <blockquote><pre>{@code 4909 * // instance-based implementation of the factorial function as a loop handle 4910 * static class FacLoop { 4911 * final int k; 4912 * FacLoop(int k) { this.k = k; } 4913 * int inc(int i) { return i + 1; } 4914 * int mult(int i, int acc) { return i * acc; } 4915 * boolean pred(int i) { return i < k; } 4916 * int fin(int i, int acc) { return acc; } 4917 * } 4918 * // assume MH_FacLoop is a handle to the constructor 4919 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4920 * // null initializer for counter, should initialize to 0 4921 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 4922 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 4923 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4924 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4925 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 4926 * assertEquals(5040, loop.invoke(7)); 4927 * }</pre></blockquote> 4928 * 4929 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 4930 * 4931 * @return a method handle embodying the looping behavior as defined by the arguments. 4932 * 4933 * @throws IllegalArgumentException in case any of the constraints described above is violated. 4934 * 4935 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 4936 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 4937 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 4938 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 4939 * @since 9 4940 */ 4941 public static MethodHandle loop(MethodHandle[]... clauses) { 4942 // Step 0: determine clause structure. 4943 loopChecks0(clauses); 4944 4945 List<MethodHandle> init = new ArrayList<>(); 4946 List<MethodHandle> step = new ArrayList<>(); 4947 List<MethodHandle> pred = new ArrayList<>(); 4948 List<MethodHandle> fini = new ArrayList<>(); 4949 4950 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 4951 init.add(clause[0]); // all clauses have at least length 1 4952 step.add(clause.length <= 1 ? null : clause[1]); 4953 pred.add(clause.length <= 2 ? null : clause[2]); 4954 fini.add(clause.length <= 3 ? null : clause[3]); 4955 }); 4956 4957 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 4958 final int nclauses = init.size(); 4959 4960 // Step 1A: determine iteration variables (V...). 4961 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 4962 for (int i = 0; i < nclauses; ++i) { 4963 MethodHandle in = init.get(i); 4964 MethodHandle st = step.get(i); 4965 if (in == null && st == null) { 4966 iterationVariableTypes.add(void.class); 4967 } else if (in != null && st != null) { 4968 loopChecks1a(i, in, st); 4969 iterationVariableTypes.add(in.type().returnType()); 4970 } else { 4971 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 4972 } 4973 } 4974 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). 4975 collect(Collectors.toList()); 4976 4977 // Step 1B: determine loop parameters (A...). 4978 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 4979 loopChecks1b(init, commonSuffix); 4980 4981 // Step 1C: determine loop return type. 4982 // Step 1D: check other types. 4983 // local variable required here; see JDK-8223553 4984 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 4985 .map(MethodType::returnType); 4986 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 4987 loopChecks1cd(pred, fini, loopReturnType); 4988 4989 // Step 2: determine parameter lists. 4990 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 4991 commonParameterSequence.addAll(commonSuffix); 4992 loopChecks2(step, pred, fini, commonParameterSequence); 4993 4994 // Step 3: fill in omitted functions. 4995 for (int i = 0; i < nclauses; ++i) { 4996 Class<?> t = iterationVariableTypes.get(i); 4997 if (init.get(i) == null) { 4998 init.set(i, empty(methodType(t, commonSuffix))); 4999 } 5000 if (step.get(i) == null) { 5001 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 5002 } 5003 if (pred.get(i) == null) { 5004 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence)); 5005 } 5006 if (fini.get(i) == null) { 5007 fini.set(i, empty(methodType(t, commonParameterSequence))); 5008 } 5009 } 5010 5011 // Step 4: fill in missing parameter types. 5012 // Also convert all handles to fixed-arity handles. 5013 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 5014 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 5015 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 5016 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 5017 5018 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 5019 allMatch(pl -> pl.equals(commonSuffix)); 5020 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 5021 allMatch(pl -> pl.equals(commonParameterSequence)); 5022 5023 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 5024 } 5025 5026 private static void loopChecks0(MethodHandle[][] clauses) { 5027 if (clauses == null || clauses.length == 0) { 5028 throw newIllegalArgumentException("null or no clauses passed"); 5029 } 5030 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 5031 throw newIllegalArgumentException("null clauses are not allowed"); 5032 } 5033 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 5034 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 5035 } 5036 } 5037 5038 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 5039 if (in.type().returnType() != st.type().returnType()) { 5040 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 5041 st.type().returnType()); 5042 } 5043 } 5044 5045 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 5046 final List<Class<?>> empty = List.of(); 5047 final List<Class<?>> longest = mhs.filter(Objects::nonNull). 5048 // take only those that can contribute to a common suffix because they are longer than the prefix 5049 map(MethodHandle::type). 5050 filter(t -> t.parameterCount() > skipSize). 5051 map(MethodType::parameterList). 5052 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 5053 return longest.size() == 0 ? empty : longest.subList(skipSize, longest.size()); 5054 } 5055 5056 private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) { 5057 final List<Class<?>> empty = List.of(); 5058 return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 5059 } 5060 5061 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 5062 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 5063 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 5064 return longestParameterList(Arrays.asList(longest1, longest2)); 5065 } 5066 5067 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 5068 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 5069 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 5070 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 5071 " (common suffix: " + commonSuffix + ")"); 5072 } 5073 } 5074 5075 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 5076 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 5077 anyMatch(t -> t != loopReturnType)) { 5078 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 5079 loopReturnType + ")"); 5080 } 5081 5082 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { 5083 throw newIllegalArgumentException("no predicate found", pred); 5084 } 5085 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 5086 anyMatch(t -> t != boolean.class)) { 5087 throw newIllegalArgumentException("predicates must have boolean return type", pred); 5088 } 5089 } 5090 5091 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 5092 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 5093 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 5094 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 5095 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 5096 } 5097 } 5098 5099 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 5100 return hs.stream().map(h -> { 5101 int pc = h.type().parameterCount(); 5102 int tpsize = targetParams.size(); 5103 return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h; 5104 }).collect(Collectors.toList()); 5105 } 5106 5107 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 5108 return hs.stream().map(MethodHandle::asFixedArity).collect(Collectors.toList()); 5109 } 5110 5111 /** 5112 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 5113 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5114 * <p> 5115 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 5116 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 5117 * evaluates to {@code true}). 5118 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 5119 * <p> 5120 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 5121 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 5122 * and updated with the value returned from its invocation. The result of loop execution will be 5123 * the final value of the additional loop-local variable (if present). 5124 * <p> 5125 * The following rules hold for these argument handles:<ul> 5126 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5127 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 5128 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5129 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 5130 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 5131 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 5132 * It will constrain the parameter lists of the other loop parts. 5133 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 5134 * list {@code (A...)} is called the <em>external parameter list</em>. 5135 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5136 * additional state variable of the loop. 5137 * The body must both accept and return a value of this type {@code V}. 5138 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5139 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5140 * <a href="MethodHandles.html#effid">effectively identical</a> 5141 * to the external parameter list {@code (A...)}. 5142 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5143 * {@linkplain #empty default value}. 5144 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 5145 * Its parameter list (either empty or of the form {@code (V A*)}) must be 5146 * effectively identical to the internal parameter list. 5147 * </ul> 5148 * <p> 5149 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5150 * <li>The loop handle's result type is the result type {@code V} of the body. 5151 * <li>The loop handle's parameter types are the types {@code (A...)}, 5152 * from the external parameter list. 5153 * </ul> 5154 * <p> 5155 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5156 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 5157 * passed to the loop. 5158 * <blockquote><pre>{@code 5159 * V init(A...); 5160 * boolean pred(V, A...); 5161 * V body(V, A...); 5162 * V whileLoop(A... a...) { 5163 * V v = init(a...); 5164 * while (pred(v, a...)) { 5165 * v = body(v, a...); 5166 * } 5167 * return v; 5168 * } 5169 * }</pre></blockquote> 5170 * 5171 * @apiNote Example: 5172 * <blockquote><pre>{@code 5173 * // implement the zip function for lists as a loop handle 5174 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 5175 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 5176 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 5177 * zip.add(a.next()); 5178 * zip.add(b.next()); 5179 * return zip; 5180 * } 5181 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 5182 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 5183 * List<String> a = Arrays.asList("a", "b", "c", "d"); 5184 * List<String> b = Arrays.asList("e", "f", "g", "h"); 5185 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 5186 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 5187 * }</pre></blockquote> 5188 * 5189 * 5190 * @apiNote The implementation of this method can be expressed as follows: 5191 * <blockquote><pre>{@code 5192 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 5193 * MethodHandle fini = (body.type().returnType() == void.class 5194 * ? null : identity(body.type().returnType())); 5195 * MethodHandle[] 5196 * checkExit = { null, null, pred, fini }, 5197 * varBody = { init, body }; 5198 * return loop(checkExit, varBody); 5199 * } 5200 * }</pre></blockquote> 5201 * 5202 * @param init optional initializer, providing the initial value of the loop variable. 5203 * May be {@code null}, implying a default initial value. See above for other constraints. 5204 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 5205 * above for other constraints. 5206 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 5207 * See above for other constraints. 5208 * 5209 * @return a method handle implementing the {@code while} loop as described by the arguments. 5210 * @throws IllegalArgumentException if the rules for the arguments are violated. 5211 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 5212 * 5213 * @see #loop(MethodHandle[][]) 5214 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 5215 * @since 9 5216 */ 5217 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 5218 whileLoopChecks(init, pred, body); 5219 MethodHandle fini = identityOrVoid(body.type().returnType()); 5220 MethodHandle[] checkExit = { null, null, pred, fini }; 5221 MethodHandle[] varBody = { init, body }; 5222 return loop(checkExit, varBody); 5223 } 5224 5225 /** 5226 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 5227 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5228 * <p> 5229 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 5230 * method will, in each iteration, first execute its body and then evaluate the predicate. 5231 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 5232 * <p> 5233 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 5234 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 5235 * and updated with the value returned from its invocation. The result of loop execution will be 5236 * the final value of the additional loop-local variable (if present). 5237 * <p> 5238 * The following rules hold for these argument handles:<ul> 5239 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5240 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 5241 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5242 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 5243 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 5244 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 5245 * It will constrain the parameter lists of the other loop parts. 5246 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 5247 * list {@code (A...)} is called the <em>external parameter list</em>. 5248 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5249 * additional state variable of the loop. 5250 * The body must both accept and return a value of this type {@code V}. 5251 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5252 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5253 * <a href="MethodHandles.html#effid">effectively identical</a> 5254 * to the external parameter list {@code (A...)}. 5255 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5256 * {@linkplain #empty default value}. 5257 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 5258 * Its parameter list (either empty or of the form {@code (V A*)}) must be 5259 * effectively identical to the internal parameter list. 5260 * </ul> 5261 * <p> 5262 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5263 * <li>The loop handle's result type is the result type {@code V} of the body. 5264 * <li>The loop handle's parameter types are the types {@code (A...)}, 5265 * from the external parameter list. 5266 * </ul> 5267 * <p> 5268 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5269 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 5270 * passed to the loop. 5271 * <blockquote><pre>{@code 5272 * V init(A...); 5273 * boolean pred(V, A...); 5274 * V body(V, A...); 5275 * V doWhileLoop(A... a...) { 5276 * V v = init(a...); 5277 * do { 5278 * v = body(v, a...); 5279 * } while (pred(v, a...)); 5280 * return v; 5281 * } 5282 * }</pre></blockquote> 5283 * 5284 * @apiNote Example: 5285 * <blockquote><pre>{@code 5286 * // int i = 0; while (i < limit) { ++i; } return i; => limit 5287 * static int zero(int limit) { return 0; } 5288 * static int step(int i, int limit) { return i + 1; } 5289 * static boolean pred(int i, int limit) { return i < limit; } 5290 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 5291 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 5292 * assertEquals(23, loop.invoke(23)); 5293 * }</pre></blockquote> 5294 * 5295 * 5296 * @apiNote The implementation of this method can be expressed as follows: 5297 * <blockquote><pre>{@code 5298 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 5299 * MethodHandle fini = (body.type().returnType() == void.class 5300 * ? null : identity(body.type().returnType())); 5301 * MethodHandle[] clause = { init, body, pred, fini }; 5302 * return loop(clause); 5303 * } 5304 * }</pre></blockquote> 5305 * 5306 * @param init optional initializer, providing the initial value of the loop variable. 5307 * May be {@code null}, implying a default initial value. See above for other constraints. 5308 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 5309 * See above for other constraints. 5310 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 5311 * above for other constraints. 5312 * 5313 * @return a method handle implementing the {@code while} loop as described by the arguments. 5314 * @throws IllegalArgumentException if the rules for the arguments are violated. 5315 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 5316 * 5317 * @see #loop(MethodHandle[][]) 5318 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 5319 * @since 9 5320 */ 5321 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 5322 whileLoopChecks(init, pred, body); 5323 MethodHandle fini = identityOrVoid(body.type().returnType()); 5324 MethodHandle[] clause = {init, body, pred, fini }; 5325 return loop(clause); 5326 } 5327 5328 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 5329 Objects.requireNonNull(pred); 5330 Objects.requireNonNull(body); 5331 MethodType bodyType = body.type(); 5332 Class<?> returnType = bodyType.returnType(); 5333 List<Class<?>> innerList = bodyType.parameterList(); 5334 List<Class<?>> outerList = innerList; 5335 if (returnType == void.class) { 5336 // OK 5337 } else if (innerList.size() == 0 || innerList.get(0) != returnType) { 5338 // leading V argument missing => error 5339 MethodType expected = bodyType.insertParameterTypes(0, returnType); 5340 throw misMatchedTypes("body function", bodyType, expected); 5341 } else { 5342 outerList = innerList.subList(1, innerList.size()); 5343 } 5344 MethodType predType = pred.type(); 5345 if (predType.returnType() != boolean.class || 5346 !predType.effectivelyIdenticalParameters(0, innerList)) { 5347 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 5348 } 5349 if (init != null) { 5350 MethodType initType = init.type(); 5351 if (initType.returnType() != returnType || 5352 !initType.effectivelyIdenticalParameters(0, outerList)) { 5353 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 5354 } 5355 } 5356 } 5357 5358 /** 5359 * Constructs a loop that runs a given number of iterations. 5360 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5361 * <p> 5362 * The number of iterations is determined by the {@code iterations} handle evaluation result. 5363 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 5364 * It will be initialized to 0 and incremented by 1 in each iteration. 5365 * <p> 5366 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 5367 * of that type is also present. This variable is initialized using the optional {@code init} handle, 5368 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 5369 * <p> 5370 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 5371 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 5372 * iteration variable. 5373 * The result of the loop handle execution will be the final {@code V} value of that variable 5374 * (or {@code void} if there is no {@code V} variable). 5375 * <p> 5376 * The following rules hold for the argument handles:<ul> 5377 * <li>The {@code iterations} handle must not be {@code null}, and must return 5378 * the type {@code int}, referred to here as {@code I} in parameter type lists. 5379 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5380 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 5381 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5382 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 5383 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 5384 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 5385 * of types called the <em>internal parameter list</em>. 5386 * It will constrain the parameter lists of the other loop parts. 5387 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 5388 * with no additional {@code A} types, then the internal parameter list is extended by 5389 * the argument types {@code A...} of the {@code iterations} handle. 5390 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 5391 * list {@code (A...)} is called the <em>external parameter list</em>. 5392 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5393 * additional state variable of the loop. 5394 * The body must both accept a leading parameter and return a value of this type {@code V}. 5395 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5396 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5397 * <a href="MethodHandles.html#effid">effectively identical</a> 5398 * to the external parameter list {@code (A...)}. 5399 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5400 * {@linkplain #empty default value}. 5401 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 5402 * effectively identical to the external parameter list {@code (A...)}. 5403 * </ul> 5404 * <p> 5405 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5406 * <li>The loop handle's result type is the result type {@code V} of the body. 5407 * <li>The loop handle's parameter types are the types {@code (A...)}, 5408 * from the external parameter list. 5409 * </ul> 5410 * <p> 5411 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5412 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 5413 * arguments passed to the loop. 5414 * <blockquote><pre>{@code 5415 * int iterations(A...); 5416 * V init(A...); 5417 * V body(V, int, A...); 5418 * V countedLoop(A... a...) { 5419 * int end = iterations(a...); 5420 * V v = init(a...); 5421 * for (int i = 0; i < end; ++i) { 5422 * v = body(v, i, a...); 5423 * } 5424 * return v; 5425 * } 5426 * }</pre></blockquote> 5427 * 5428 * @apiNote Example with a fully conformant body method: 5429 * <blockquote><pre>{@code 5430 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 5431 * // => a variation on a well known theme 5432 * static String step(String v, int counter, String init) { return "na " + v; } 5433 * // assume MH_step is a handle to the method above 5434 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 5435 * MethodHandle start = MethodHandles.identity(String.class); 5436 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 5437 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 5438 * }</pre></blockquote> 5439 * 5440 * @apiNote Example with the simplest possible body method type, 5441 * and passing the number of iterations to the loop invocation: 5442 * <blockquote><pre>{@code 5443 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 5444 * // => a variation on a well known theme 5445 * static String step(String v, int counter ) { return "na " + v; } 5446 * // assume MH_step is a handle to the method above 5447 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 5448 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 5449 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 5450 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 5451 * }</pre></blockquote> 5452 * 5453 * @apiNote Example that treats the number of iterations, string to append to, and string to append 5454 * as loop parameters: 5455 * <blockquote><pre>{@code 5456 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 5457 * // => a variation on a well known theme 5458 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 5459 * // assume MH_step is a handle to the method above 5460 * MethodHandle count = MethodHandles.identity(int.class); 5461 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 5462 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 5463 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 5464 * }</pre></blockquote> 5465 * 5466 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 5467 * to enforce a loop type: 5468 * <blockquote><pre>{@code 5469 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 5470 * // => a variation on a well known theme 5471 * static String step(String v, int counter, String pre) { return pre + " " + v; } 5472 * // assume MH_step is a handle to the method above 5473 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 5474 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 5475 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 5476 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 5477 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 5478 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 5479 * }</pre></blockquote> 5480 * 5481 * @apiNote The implementation of this method can be expressed as follows: 5482 * <blockquote><pre>{@code 5483 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 5484 * return countedLoop(empty(iterations.type()), iterations, init, body); 5485 * } 5486 * }</pre></blockquote> 5487 * 5488 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 5489 * result type must be {@code int}. See above for other constraints. 5490 * @param init optional initializer, providing the initial value of the loop variable. 5491 * May be {@code null}, implying a default initial value. See above for other constraints. 5492 * @param body body of the loop, which may not be {@code null}. 5493 * It controls the loop parameters and result type in the standard case (see above for details). 5494 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 5495 * and may accept any number of additional types. 5496 * See above for other constraints. 5497 * 5498 * @return a method handle representing the loop. 5499 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 5500 * @throws IllegalArgumentException if any argument violates the rules formulated above. 5501 * 5502 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 5503 * @since 9 5504 */ 5505 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 5506 return countedLoop(empty(iterations.type()), iterations, init, body); 5507 } 5508 5509 /** 5510 * Constructs a loop that counts over a range of numbers. 5511 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5512 * <p> 5513 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 5514 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 5515 * values of the loop counter. 5516 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 5517 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 5518 * <p> 5519 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 5520 * of that type is also present. This variable is initialized using the optional {@code init} handle, 5521 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 5522 * <p> 5523 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 5524 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 5525 * iteration variable. 5526 * The result of the loop handle execution will be the final {@code V} value of that variable 5527 * (or {@code void} if there is no {@code V} variable). 5528 * <p> 5529 * The following rules hold for the argument handles:<ul> 5530 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 5531 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 5532 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5533 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 5534 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5535 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 5536 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 5537 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 5538 * of types called the <em>internal parameter list</em>. 5539 * It will constrain the parameter lists of the other loop parts. 5540 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 5541 * with no additional {@code A} types, then the internal parameter list is extended by 5542 * the argument types {@code A...} of the {@code end} handle. 5543 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 5544 * list {@code (A...)} is called the <em>external parameter list</em>. 5545 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5546 * additional state variable of the loop. 5547 * The body must both accept a leading parameter and return a value of this type {@code V}. 5548 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5549 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5550 * <a href="MethodHandles.html#effid">effectively identical</a> 5551 * to the external parameter list {@code (A...)}. 5552 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5553 * {@linkplain #empty default value}. 5554 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 5555 * effectively identical to the external parameter list {@code (A...)}. 5556 * <li>Likewise, the parameter list of {@code end} must be effectively identical 5557 * to the external parameter list. 5558 * </ul> 5559 * <p> 5560 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5561 * <li>The loop handle's result type is the result type {@code V} of the body. 5562 * <li>The loop handle's parameter types are the types {@code (A...)}, 5563 * from the external parameter list. 5564 * </ul> 5565 * <p> 5566 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5567 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 5568 * arguments passed to the loop. 5569 * <blockquote><pre>{@code 5570 * int start(A...); 5571 * int end(A...); 5572 * V init(A...); 5573 * V body(V, int, A...); 5574 * V countedLoop(A... a...) { 5575 * int e = end(a...); 5576 * int s = start(a...); 5577 * V v = init(a...); 5578 * for (int i = s; i < e; ++i) { 5579 * v = body(v, i, a...); 5580 * } 5581 * return v; 5582 * } 5583 * }</pre></blockquote> 5584 * 5585 * @apiNote The implementation of this method can be expressed as follows: 5586 * <blockquote><pre>{@code 5587 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 5588 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 5589 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 5590 * // the following semantics: 5591 * // MH_increment: (int limit, int counter) -> counter + 1 5592 * // MH_predicate: (int limit, int counter) -> counter < limit 5593 * Class<?> counterType = start.type().returnType(); // int 5594 * Class<?> returnType = body.type().returnType(); 5595 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 5596 * if (returnType != void.class) { // ignore the V variable 5597 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 5598 * pred = dropArguments(pred, 1, returnType); // ditto 5599 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 5600 * } 5601 * body = dropArguments(body, 0, counterType); // ignore the limit variable 5602 * MethodHandle[] 5603 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 5604 * bodyClause = { init, body }, // v = init(); v = body(v, i) 5605 * indexVar = { start, incr }; // i = start(); i = i + 1 5606 * return loop(loopLimit, bodyClause, indexVar); 5607 * } 5608 * }</pre></blockquote> 5609 * 5610 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 5611 * See above for other constraints. 5612 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 5613 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 5614 * @param init optional initializer, providing the initial value of the loop variable. 5615 * May be {@code null}, implying a default initial value. See above for other constraints. 5616 * @param body body of the loop, which may not be {@code null}. 5617 * It controls the loop parameters and result type in the standard case (see above for details). 5618 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 5619 * and may accept any number of additional types. 5620 * See above for other constraints. 5621 * 5622 * @return a method handle representing the loop. 5623 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 5624 * @throws IllegalArgumentException if any argument violates the rules formulated above. 5625 * 5626 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 5627 * @since 9 5628 */ 5629 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 5630 countedLoopChecks(start, end, init, body); 5631 Class<?> counterType = start.type().returnType(); // int, but who's counting? 5632 Class<?> limitType = end.type().returnType(); // yes, int again 5633 Class<?> returnType = body.type().returnType(); 5634 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 5635 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 5636 MethodHandle retv = null; 5637 if (returnType != void.class) { 5638 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 5639 pred = dropArguments(pred, 1, returnType); // ditto 5640 retv = dropArguments(identity(returnType), 0, counterType); 5641 } 5642 body = dropArguments(body, 0, counterType); // ignore the limit variable 5643 MethodHandle[] 5644 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 5645 bodyClause = { init, body }, // v = init(); v = body(v, i) 5646 indexVar = { start, incr }; // i = start(); i = i + 1 5647 return loop(loopLimit, bodyClause, indexVar); 5648 } 5649 5650 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 5651 Objects.requireNonNull(start); 5652 Objects.requireNonNull(end); 5653 Objects.requireNonNull(body); 5654 Class<?> counterType = start.type().returnType(); 5655 if (counterType != int.class) { 5656 MethodType expected = start.type().changeReturnType(int.class); 5657 throw misMatchedTypes("start function", start.type(), expected); 5658 } else if (end.type().returnType() != counterType) { 5659 MethodType expected = end.type().changeReturnType(counterType); 5660 throw misMatchedTypes("end function", end.type(), expected); 5661 } 5662 MethodType bodyType = body.type(); 5663 Class<?> returnType = bodyType.returnType(); 5664 List<Class<?>> innerList = bodyType.parameterList(); 5665 // strip leading V value if present 5666 int vsize = (returnType == void.class ? 0 : 1); 5667 if (vsize != 0 && (innerList.size() == 0 || innerList.get(0) != returnType)) { 5668 // argument list has no "V" => error 5669 MethodType expected = bodyType.insertParameterTypes(0, returnType); 5670 throw misMatchedTypes("body function", bodyType, expected); 5671 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 5672 // missing I type => error 5673 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 5674 throw misMatchedTypes("body function", bodyType, expected); 5675 } 5676 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 5677 if (outerList.isEmpty()) { 5678 // special case; take lists from end handle 5679 outerList = end.type().parameterList(); 5680 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 5681 } 5682 MethodType expected = methodType(counterType, outerList); 5683 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 5684 throw misMatchedTypes("start parameter types", start.type(), expected); 5685 } 5686 if (end.type() != start.type() && 5687 !end.type().effectivelyIdenticalParameters(0, outerList)) { 5688 throw misMatchedTypes("end parameter types", end.type(), expected); 5689 } 5690 if (init != null) { 5691 MethodType initType = init.type(); 5692 if (initType.returnType() != returnType || 5693 !initType.effectivelyIdenticalParameters(0, outerList)) { 5694 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 5695 } 5696 } 5697 } 5698 5699 /** 5700 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 5701 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5702 * <p> 5703 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 5704 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 5705 * <p> 5706 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 5707 * of that type is also present. This variable is initialized using the optional {@code init} handle, 5708 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 5709 * <p> 5710 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 5711 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 5712 * iteration variable. 5713 * The result of the loop handle execution will be the final {@code V} value of that variable 5714 * (or {@code void} if there is no {@code V} variable). 5715 * <p> 5716 * The following rules hold for the argument handles:<ul> 5717 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5718 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 5719 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5720 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 5721 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 5722 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 5723 * of types called the <em>internal parameter list</em>. 5724 * It will constrain the parameter lists of the other loop parts. 5725 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 5726 * with no additional {@code A} types, then the internal parameter list is extended by 5727 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 5728 * single type {@code Iterable} is added and constitutes the {@code A...} list. 5729 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 5730 * list {@code (A...)} is called the <em>external parameter list</em>. 5731 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5732 * additional state variable of the loop. 5733 * The body must both accept a leading parameter and return a value of this type {@code V}. 5734 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5735 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5736 * <a href="MethodHandles.html#effid">effectively identical</a> 5737 * to the external parameter list {@code (A...)}. 5738 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5739 * {@linkplain #empty default value}. 5740 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 5741 * type {@code java.util.Iterator} or a subtype thereof. 5742 * The iterator it produces when the loop is executed will be assumed 5743 * to yield values which can be converted to type {@code T}. 5744 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 5745 * effectively identical to the external parameter list {@code (A...)}. 5746 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 5747 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 5748 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 5749 * handle parameter is adjusted to accept the leading {@code A} type, as if by 5750 * the {@link MethodHandle#asType asType} conversion method. 5751 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 5752 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 5753 * </ul> 5754 * <p> 5755 * The type {@code T} may be either a primitive or reference. 5756 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 5757 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 5758 * as if by the {@link MethodHandle#asType asType} conversion method. 5759 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 5760 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 5761 * <p> 5762 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5763 * <li>The loop handle's result type is the result type {@code V} of the body. 5764 * <li>The loop handle's parameter types are the types {@code (A...)}, 5765 * from the external parameter list. 5766 * </ul> 5767 * <p> 5768 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5769 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 5770 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 5771 * <blockquote><pre>{@code 5772 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 5773 * V init(A...); 5774 * V body(V,T,A...); 5775 * V iteratedLoop(A... a...) { 5776 * Iterator<T> it = iterator(a...); 5777 * V v = init(a...); 5778 * while (it.hasNext()) { 5779 * T t = it.next(); 5780 * v = body(v, t, a...); 5781 * } 5782 * return v; 5783 * } 5784 * }</pre></blockquote> 5785 * 5786 * @apiNote Example: 5787 * <blockquote><pre>{@code 5788 * // get an iterator from a list 5789 * static List<String> reverseStep(List<String> r, String e) { 5790 * r.add(0, e); 5791 * return r; 5792 * } 5793 * static List<String> newArrayList() { return new ArrayList<>(); } 5794 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 5795 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 5796 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 5797 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 5798 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 5799 * }</pre></blockquote> 5800 * 5801 * @apiNote The implementation of this method can be expressed approximately as follows: 5802 * <blockquote><pre>{@code 5803 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 5804 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 5805 * Class<?> returnType = body.type().returnType(); 5806 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 5807 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 5808 * MethodHandle retv = null, step = body, startIter = iterator; 5809 * if (returnType != void.class) { 5810 * // the simple thing first: in (I V A...), drop the I to get V 5811 * retv = dropArguments(identity(returnType), 0, Iterator.class); 5812 * // body type signature (V T A...), internal loop types (I V A...) 5813 * step = swapArguments(body, 0, 1); // swap V <-> T 5814 * } 5815 * if (startIter == null) startIter = MH_getIter; 5816 * MethodHandle[] 5817 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 5818 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 5819 * return loop(iterVar, bodyClause); 5820 * } 5821 * }</pre></blockquote> 5822 * 5823 * @param iterator an optional handle to return the iterator to start the loop. 5824 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 5825 * See above for other constraints. 5826 * @param init optional initializer, providing the initial value of the loop variable. 5827 * May be {@code null}, implying a default initial value. See above for other constraints. 5828 * @param body body of the loop, which may not be {@code null}. 5829 * It controls the loop parameters and result type in the standard case (see above for details). 5830 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 5831 * and may accept any number of additional types. 5832 * See above for other constraints. 5833 * 5834 * @return a method handle embodying the iteration loop functionality. 5835 * @throws NullPointerException if the {@code body} handle is {@code null}. 5836 * @throws IllegalArgumentException if any argument violates the above requirements. 5837 * 5838 * @since 9 5839 */ 5840 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 5841 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 5842 Class<?> returnType = body.type().returnType(); 5843 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 5844 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 5845 MethodHandle startIter; 5846 MethodHandle nextVal; 5847 { 5848 MethodType iteratorType; 5849 if (iterator == null) { 5850 // derive argument type from body, if available, else use Iterable 5851 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 5852 iteratorType = startIter.type().changeParameterType(0, iterableType); 5853 } else { 5854 // force return type to the internal iterator class 5855 iteratorType = iterator.type().changeReturnType(Iterator.class); 5856 startIter = iterator; 5857 } 5858 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 5859 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 5860 5861 // perform the asType transforms under an exception transformer, as per spec.: 5862 try { 5863 startIter = startIter.asType(iteratorType); 5864 nextVal = nextRaw.asType(nextValType); 5865 } catch (WrongMethodTypeException ex) { 5866 throw new IllegalArgumentException(ex); 5867 } 5868 } 5869 5870 MethodHandle retv = null, step = body; 5871 if (returnType != void.class) { 5872 // the simple thing first: in (I V A...), drop the I to get V 5873 retv = dropArguments(identity(returnType), 0, Iterator.class); 5874 // body type signature (V T A...), internal loop types (I V A...) 5875 step = swapArguments(body, 0, 1); // swap V <-> T 5876 } 5877 5878 MethodHandle[] 5879 iterVar = { startIter, null, hasNext, retv }, 5880 bodyClause = { init, filterArgument(step, 0, nextVal) }; 5881 return loop(iterVar, bodyClause); 5882 } 5883 5884 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 5885 Objects.requireNonNull(body); 5886 MethodType bodyType = body.type(); 5887 Class<?> returnType = bodyType.returnType(); 5888 List<Class<?>> internalParamList = bodyType.parameterList(); 5889 // strip leading V value if present 5890 int vsize = (returnType == void.class ? 0 : 1); 5891 if (vsize != 0 && (internalParamList.size() == 0 || internalParamList.get(0) != returnType)) { 5892 // argument list has no "V" => error 5893 MethodType expected = bodyType.insertParameterTypes(0, returnType); 5894 throw misMatchedTypes("body function", bodyType, expected); 5895 } else if (internalParamList.size() <= vsize) { 5896 // missing T type => error 5897 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 5898 throw misMatchedTypes("body function", bodyType, expected); 5899 } 5900 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 5901 Class<?> iterableType = null; 5902 if (iterator != null) { 5903 // special case; if the body handle only declares V and T then 5904 // the external parameter list is obtained from iterator handle 5905 if (externalParamList.isEmpty()) { 5906 externalParamList = iterator.type().parameterList(); 5907 } 5908 MethodType itype = iterator.type(); 5909 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 5910 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 5911 } 5912 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 5913 MethodType expected = methodType(itype.returnType(), externalParamList); 5914 throw misMatchedTypes("iterator parameters", itype, expected); 5915 } 5916 } else { 5917 if (externalParamList.isEmpty()) { 5918 // special case; if the iterator handle is null and the body handle 5919 // only declares V and T then the external parameter list consists 5920 // of Iterable 5921 externalParamList = Arrays.asList(Iterable.class); 5922 iterableType = Iterable.class; 5923 } else { 5924 // special case; if the iterator handle is null and the external 5925 // parameter list is not empty then the first parameter must be 5926 // assignable to Iterable 5927 iterableType = externalParamList.get(0); 5928 if (!Iterable.class.isAssignableFrom(iterableType)) { 5929 throw newIllegalArgumentException( 5930 "inferred first loop argument must inherit from Iterable: " + iterableType); 5931 } 5932 } 5933 } 5934 if (init != null) { 5935 MethodType initType = init.type(); 5936 if (initType.returnType() != returnType || 5937 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 5938 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 5939 } 5940 } 5941 return iterableType; // help the caller a bit 5942 } 5943 5944 /*non-public*/ static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 5945 // there should be a better way to uncross my wires 5946 int arity = mh.type().parameterCount(); 5947 int[] order = new int[arity]; 5948 for (int k = 0; k < arity; k++) order[k] = k; 5949 order[i] = j; order[j] = i; 5950 Class<?>[] types = mh.type().parameterArray(); 5951 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 5952 MethodType swapType = methodType(mh.type().returnType(), types); 5953 return permuteArguments(mh, swapType, order); 5954 } 5955 5956 /** 5957 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 5958 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 5959 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 5960 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 5961 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 5962 * {@code try-finally} handle. 5963 * <p> 5964 * The {@code cleanup} handle will be passed one or two additional leading arguments. 5965 * The first is the exception thrown during the 5966 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 5967 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 5968 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 5969 * The second argument is not present if the {@code target} handle has a {@code void} return type. 5970 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 5971 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 5972 * <p> 5973 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 5974 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 5975 * two extra leading parameters:<ul> 5976 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 5977 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 5978 * the result from the execution of the {@code target} handle. 5979 * This parameter is not present if the {@code target} returns {@code void}. 5980 * </ul> 5981 * <p> 5982 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 5983 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 5984 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 5985 * the cleanup. 5986 * <blockquote><pre>{@code 5987 * V target(A..., B...); 5988 * V cleanup(Throwable, V, A...); 5989 * V adapter(A... a, B... b) { 5990 * V result = (zero value for V); 5991 * Throwable throwable = null; 5992 * try { 5993 * result = target(a..., b...); 5994 * } catch (Throwable t) { 5995 * throwable = t; 5996 * throw t; 5997 * } finally { 5998 * result = cleanup(throwable, result, a...); 5999 * } 6000 * return result; 6001 * } 6002 * }</pre></blockquote> 6003 * <p> 6004 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6005 * be modified by execution of the target, and so are passed unchanged 6006 * from the caller to the cleanup, if it is invoked. 6007 * <p> 6008 * The target and cleanup must return the same type, even if the cleanup 6009 * always throws. 6010 * To create such a throwing cleanup, compose the cleanup logic 6011 * with {@link #throwException throwException}, 6012 * in order to create a method handle of the correct return type. 6013 * <p> 6014 * Note that {@code tryFinally} never converts exceptions into normal returns. 6015 * In rare cases where exceptions must be converted in that way, first wrap 6016 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 6017 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 6018 * <p> 6019 * It is recommended that the first parameter type of {@code cleanup} be 6020 * declared {@code Throwable} rather than a narrower subtype. This ensures 6021 * {@code cleanup} will always be invoked with whatever exception that 6022 * {@code target} throws. Declaring a narrower type may result in a 6023 * {@code ClassCastException} being thrown by the {@code try-finally} 6024 * handle if the type of the exception thrown by {@code target} is not 6025 * assignable to the first parameter type of {@code cleanup}. Note that 6026 * various exception types of {@code VirtualMachineError}, 6027 * {@code LinkageError}, and {@code RuntimeException} can in principle be 6028 * thrown by almost any kind of Java code, and a finally clause that 6029 * catches (say) only {@code IOException} would mask any of the others 6030 * behind a {@code ClassCastException}. 6031 * 6032 * @param target the handle whose execution is to be wrapped in a {@code try} block. 6033 * @param cleanup the handle that is invoked in the finally block. 6034 * 6035 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 6036 * @throws NullPointerException if any argument is null 6037 * @throws IllegalArgumentException if {@code cleanup} does not accept 6038 * the required leading arguments, or if the method handle types do 6039 * not match in their return types and their 6040 * corresponding trailing parameters 6041 * 6042 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 6043 * @since 9 6044 */ 6045 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 6046 List<Class<?>> targetParamTypes = target.type().parameterList(); 6047 Class<?> rtype = target.type().returnType(); 6048 6049 tryFinallyChecks(target, cleanup); 6050 6051 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 6052 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 6053 // target parameter list. 6054 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); 6055 6056 // Ensure that the intrinsic type checks the instance thrown by the 6057 // target against the first parameter of cleanup 6058 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 6059 6060 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 6061 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 6062 } 6063 6064 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 6065 Class<?> rtype = target.type().returnType(); 6066 if (rtype != cleanup.type().returnType()) { 6067 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 6068 } 6069 MethodType cleanupType = cleanup.type(); 6070 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 6071 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 6072 } 6073 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 6074 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 6075 } 6076 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 6077 // target parameter list. 6078 int cleanupArgIndex = rtype == void.class ? 1 : 2; 6079 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 6080 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 6081 cleanup.type(), target.type()); 6082 } 6083 } 6084 6085 }