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