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