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