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