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