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 that is guaranteed to be unique 1785 * during this execution of the JVM. 1786 * 1787 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1788 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1789 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1790 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1791 * refers to the new {@code CONSTANT_Utf8_info} structure. 1792 * 1793 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1794 * 1795 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1796 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1797 * with the following adjustments: 1798 * <ul> 1799 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1800 * that includes a single {@code "."} character, even though this is not a valid 1801 * binary class or interface name in internal form.</li> 1802 * 1803 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1804 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1805 * 1806 * <li> {@code C} is considered to have the same runtime 1807 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1808 * and {@linkplain java.security.ProtectionDomain protection domain} 1809 * as the lookup class of this {@code Lookup}. 1810 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1811 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1812 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}, 1813 * {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, even though 1814 * this is not a valid binary class or interface name.</li> 1815 * </ul> 1816 * </li> 1817 * </ol> 1818 * 1819 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1820 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1821 * <ul> 1822 * <li> During verification, whenever it is necessary to load the class named 1823 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 1824 * made of any class loader.</li> 1825 * 1826 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 1827 * by {@code this_class}, the symbolic reference is considered to be resolved to 1828 * {@code C} and resolution always succeeds immediately.</li> 1829 * </ul> 1830 * 1831 * <p> If the {@code initialize} parameter is {@code true}, 1832 * then {@code C} is initialized by the Java Virtual Machine. 1833 * 1834 * <p> The newly created class or interface {@code C} serves as the 1835 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 1836 * returned by this method. {@code C} is <em>hidden</em> in the sense that 1837 * no other class or interface can refer to {@code C} via a constant pool entry. 1838 * That is, a hidden class or interface cannot be named as a supertype, a field type, 1839 * a method parameter type, or a method return type by any other class. 1840 * This is because a hidden class or interface does not have a binary name, so 1841 * there is no internal form available to record in any class's constant pool. 1842 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 1843 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 1844 * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class) 1845 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 1846 * JVM Tool Interface</a>. 1847 * 1848 * <p> A class or interface created by 1849 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1850 * a class loader} has a strong relationship with that class loader. 1851 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 1852 * that {@linkplain Class#getClassLoader() defined it}. 1853 * This means that a class created by a class loader may be unloaded if and 1854 * only if its defining loader is not reachable and thus may be reclaimed 1855 * by a garbage collector (JLS 12.7). 1856 * 1857 * By default, however, a hidden class or interface may be unloaded even if 1858 * the class loader that is marked as its defining loader is 1859 * <a href="../ref/package.html#reachability">reachable</a>. 1860 * This behavior is useful when a hidden class or interface serves multiple 1861 * classes defined by arbitrary class loaders. In other cases, a hidden 1862 * class or interface may be linked to a single class (or a small number of classes) 1863 * with the same defining loader as the hidden class or interface. 1864 * In such cases, where the hidden class or interface must be coterminous 1865 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 1866 * option may be passed in {@code options}. 1867 * This arranges for a hidden class to have the same strong relationship 1868 * with the class loader marked as its defining loader, 1869 * as a normal class or interface has with its own defining loader. 1870 * 1871 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 1872 * may still prevent a hidden class or interface from being 1873 * unloaded by ensuring that the {@code Class} object is reachable. 1874 * 1875 * <p> The unloading characteristics are set for each hidden class when it is 1876 * defined, and cannot be changed later. An advantage of allowing hidden classes 1877 * to be unloaded independently of the class loader marked as their defining loader 1878 * is that a very large number of hidden classes may be created by an application. 1879 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 1880 * just as if normal classes were created by class loaders. 1881 * 1882 * <p> Classes and interfaces in a nest are allowed to have mutual access to 1883 * their private members. The nest relationship is determined by 1884 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 1885 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 1886 * By default, a hidden class belongs to a nest consisting only of itself 1887 * because a hidden class has no binary name. 1888 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 1889 * to create a hidden class or interface {@code C} as a member of a nest. 1890 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 1891 * in the {@code ClassFile} structure from which {@code C} was derived. 1892 * Instead, the following rules determine the nest host of {@code C}: 1893 * <ul> 1894 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 1895 * been determined, then let {@code H} be the nest host of the lookup class. 1896 * Otherwise, the nest host of the lookup class is determined using the 1897 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 1898 * <li>The nest host of {@code C} is determined to be {@code H}, 1899 * the nest host of the lookup class.</li> 1900 * </ul> 1901 * 1902 * <p> A hidden class or interface may be serializable, but this requires a custom 1903 * serialization mechanism in order to ensure that instances are properly serialized 1904 * and deserialized. The default serialization mechanism supports only classes and 1905 * interfaces that are discoverable by their class name. 1906 * 1907 * @param bytes the bytes that make up the class data, 1908 * in the format of a valid {@code class} file as defined by 1909 * <cite>The Java Virtual Machine Specification</cite>. 1910 * @param initialize if {@code true} the class will be initialized. 1911 * @param options {@linkplain ClassOption class options} 1912 * @return the {@code Lookup} object on the hidden class 1913 * 1914 * @throws IllegalAccessException if this {@code Lookup} does not have 1915 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 1916 * @throws SecurityException if a security manager is present and it 1917 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1918 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1919 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 1920 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 1921 * {@bytes} denotes a class in a different package than the lookup class 1922 * @throws IncompatibleClassChangeError if the class or interface named as 1923 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 1924 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 1925 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 1926 * {@code C} is {@code C} itself 1927 * @throws VerifyError if the newly created class cannot be verified 1928 * @throws LinkageError if the newly created class cannot be linked for any other reason 1929 * @throws NullPointerException if any parameter is {@code null} 1930 * 1931 * @since 15 1932 * @see Class#isHidden() 1933 * @jvms 4.2.1 Binary Class and Interface Names 1934 * @jvms 4.2.2 Unqualified Names 1935 * @jvms 4.7.28 The {@code NestHost} Attribute 1936 * @jvms 4.7.29 The {@code NestMembers} Attribute 1937 * @jvms 5.4.3.1 Class and Interface Resolution 1938 * @jvms 5.4.4 Access Control 1939 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 1940 * @jvms 5.4 Linking 1941 * @jvms 5.5 Initialization 1942 * @jls 12.7 Unloading of Classes and Interfaces 1943 */ 1944 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 1945 throws IllegalAccessException 1946 { 1947 Objects.requireNonNull(bytes); 1948 Objects.requireNonNull(options); 1949 1950 ensureDefineClassPermission(); 1951 if (!hasFullPrivilegeAccess()) { 1952 throw new IllegalAccessException(this + " does not have full privilege access"); 1953 } 1954 1955 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize); 1956 } 1957 1958 /** 1959 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 1960 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 1961 * returning a {@code Lookup} on the newly created class or interface. 1962 * 1963 * <p> This method is equivalent to calling 1964 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, true, options)} 1965 * as if the hidden class has a private static final unnamed field whose value 1966 * is initialized to {@code classData} right before the class initializer is 1967 * executed. The newly created class is linked and initialized by the Java 1968 * Virtual Machine. 1969 * 1970 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 1971 * method can be used to retrieve the {@code classData}. 1972 * 1973 * @param bytes the class bytes 1974 * @param classData pre-initialized class data 1975 * @param options {@linkplain ClassOption class options} 1976 * @return the {@code Lookup} object on the hidden class 1977 * 1978 * @throws IllegalAccessException if this {@code Lookup} does not have 1979 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 1980 * @throws SecurityException if a security manager is present and it 1981 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1982 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1983 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 1984 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 1985 * {@bytes} denotes a class in a different package than the lookup class 1986 * @throws IncompatibleClassChangeError if the class or interface named as 1987 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 1988 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 1989 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 1990 * {@code C} is {@code C} itself 1991 * @throws VerifyError if the newly created class cannot be verified 1992 * @throws LinkageError if the newly created class cannot be linked for any other reason 1993 * @throws NullPointerException if any parameter is {@code null} 1994 * 1995 * @since 15 1996 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1997 * @see Class#isHidden() 1998 */ 1999 /* package-private */ Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, ClassOption... options) 2000 throws IllegalAccessException 2001 { 2002 Objects.requireNonNull(bytes); 2003 Objects.requireNonNull(classData); 2004 Objects.requireNonNull(options); 2005 2006 ensureDefineClassPermission(); 2007 if (!hasFullPrivilegeAccess()) { 2008 throw new IllegalAccessException(this + " does not have full privilege access"); 2009 } 2010 2011 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false) 2012 .defineClassAsLookup(true, classData); 2013 } 2014 2015 /* 2016 * Validates the given bytes to be a class or interface and the class name 2017 * is in the same package as the lookup class. 2018 * 2019 * This method returns the class name. 2020 */ 2021 private String validateAndGetClassName(byte[] bytes) { 2022 try { 2023 ClassReader reader = new ClassReader(bytes); 2024 if ((reader.getAccess() & Opcodes.ACC_MODULE) != 0) { 2025 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2026 } 2027 String name = reader.getClassName().replace('/', '.'); 2028 int index = name.lastIndexOf('.'); 2029 String pn = (index == -1) ? "" : name.substring(0, index); 2030 if (!pn.equals(lookupClass.getPackageName())) { 2031 throw newIllegalArgumentException(name + " not in same package as lookup class: " + 2032 lookupClass.getName()); 2033 } 2034 return name; 2035 } catch (IllegalArgumentException e) { 2036 throw e; 2037 } catch (RuntimeException e) { 2038 // ASM exceptions are poorly specified 2039 ClassFormatError cfe = new ClassFormatError(); 2040 cfe.initCause(e); 2041 throw cfe; 2042 } 2043 } 2044 2045 2046 /* 2047 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2048 * from the given bytes. 2049 * 2050 * Caller should make a defensive copy of the arguments if needed 2051 * before calling this factory method. 2052 * 2053 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2054 * {@bytes} denotes a class in a different package than the lookup class 2055 */ 2056 private ClassDefiner makeClassDefiner(byte[] bytes) { 2057 return new ClassDefiner(this, validateAndGetClassName(bytes), bytes, STRONG_LOADER_LINK); 2058 } 2059 2060 /** 2061 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2062 * from the given bytes. The name must be in the same package as the lookup class. 2063 * 2064 * Caller should make a defensive copy of the arguments if needed 2065 * before calling this factory method. 2066 * 2067 * @param bytes class bytes 2068 * @return ClassDefiner that defines a hidden class of the given bytes. 2069 * 2070 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2071 * {@bytes} denotes a class in a different package than the lookup class 2072 */ 2073 ClassDefiner makeHiddenClassDefiner(byte[] bytes) { 2074 return makeHiddenClassDefiner(validateAndGetClassName(bytes), bytes, Set.of(), false); 2075 } 2076 2077 /** 2078 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2079 * from the given bytes and options. 2080 * The name must be in the same package as the lookup class. 2081 * 2082 * Caller should make a defensive copy of the arguments if needed 2083 * before calling this factory method. 2084 * 2085 * @param bytes class bytes 2086 * @param options class options 2087 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2088 * @return ClassDefiner that defines a hidden class of the given bytes and options 2089 * 2090 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2091 * {@bytes} denotes a class in a different package than the lookup class 2092 */ 2093 ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2094 Set<ClassOption> options, 2095 boolean accessVmAnnotations) { 2096 return makeHiddenClassDefiner(validateAndGetClassName(bytes), bytes, options, accessVmAnnotations); 2097 } 2098 2099 /** 2100 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2101 * from the given bytes. No package name check on the given name. 2102 * 2103 * @param name fully-qualified name that specifies the prefix of the hidden class 2104 * @param bytes class bytes 2105 * @return ClassDefiner that defines a hidden class of the given bytes. 2106 */ 2107 ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes) { 2108 return makeHiddenClassDefiner(name, bytes, Set.of(), false); 2109 } 2110 2111 /** 2112 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2113 * from the given bytes and options. No package name check on the given name. 2114 * 2115 * @param name the name of the class and the name in the class bytes is ignored. 2116 * @param bytes class bytes 2117 * @param options class options 2118 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2119 */ 2120 ClassDefiner makeHiddenClassDefiner(String name, 2121 byte[] bytes, 2122 Set<ClassOption> options, 2123 boolean accessVmAnnotations) { 2124 int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options); 2125 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2126 // jdk.internal.vm.annotations are permitted for classes 2127 // defined to boot loader and platform loader 2128 flags |= ACCESS_VM_ANNOTATIONS; 2129 } 2130 2131 return new ClassDefiner(this, name, bytes, flags); 2132 } 2133 2134 static class ClassDefiner { 2135 private final Lookup lookup; 2136 private final String name; 2137 private final byte[] bytes; 2138 private final int classFlags; 2139 2140 private ClassDefiner(Lookup lookup, String name, byte[] bytes, int flags) { 2141 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2142 this.lookup = lookup; 2143 this.bytes = bytes; 2144 this.classFlags = flags; 2145 this.name = name; 2146 } 2147 2148 String className() { 2149 return name; 2150 } 2151 2152 Class<?> defineClass(boolean initialize) { 2153 return defineClass(initialize, null); 2154 } 2155 2156 Lookup defineClassAsLookup(boolean initialize) { 2157 Class<?> c = defineClass(initialize, null); 2158 return new Lookup(c, null, FULL_POWER_MODES); 2159 } 2160 2161 /** 2162 * Defines the class of the given bytes and the given classData. 2163 * If {@code initialize} parameter is true, then the class will be initialized. 2164 * 2165 * @param initialize true if the class to be initialized 2166 * @param classData classData or null 2167 * @return the class 2168 * 2169 * @throws LinkageError linkage error 2170 */ 2171 Class<?> defineClass(boolean initialize, Object classData) { 2172 Class<?> lookupClass = lookup.lookupClass(); 2173 ClassLoader loader = lookupClass.getClassLoader(); 2174 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2175 Class<?> c = JLA.defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData); 2176 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2177 return c; 2178 } 2179 2180 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2181 // initialize must be true if classData is non-null 2182 assert classData == null || initialize == true; 2183 Class<?> c = defineClass(initialize, classData); 2184 return new Lookup(c, null, FULL_POWER_MODES); 2185 } 2186 2187 private boolean isNestmate() { 2188 return (classFlags & NESTMATE_CLASS) != 0; 2189 } 2190 } 2191 2192 private ProtectionDomain lookupClassProtectionDomain() { 2193 ProtectionDomain pd = cachedProtectionDomain; 2194 if (pd == null) { 2195 cachedProtectionDomain = pd = JLA.protectionDomain(lookupClass); 2196 } 2197 return pd; 2198 } 2199 2200 // cached protection domain 2201 private volatile ProtectionDomain cachedProtectionDomain; 2202 2203 // Make sure outer class is initialized first. 2204 static { IMPL_NAMES.getClass(); } 2205 2206 /** Package-private version of lookup which is trusted. */ 2207 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2208 2209 /** Version of lookup which is trusted minimally. 2210 * It can only be used to create method handles to publicly accessible 2211 * members in packages that are exported unconditionally. 2212 */ 2213 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2214 2215 static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); 2216 2217 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2218 String name = lookupClass.getName(); 2219 if (name.startsWith("java.lang.invoke.")) 2220 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2221 } 2222 2223 /** 2224 * Displays the name of the class from which lookups are to be made. 2225 * followed with "/" and the name of the {@linkplain #previousLookupClass() 2226 * previous lookup class} if present. 2227 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2228 * If there are restrictions on the access permitted to this lookup, 2229 * this is indicated by adding a suffix to the class name, consisting 2230 * of a slash and a keyword. The keyword represents the strongest 2231 * allowed access, and is chosen as follows: 2232 * <ul> 2233 * <li>If no access is allowed, the suffix is "/noaccess". 2234 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2235 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2236 * <li>If only public and module access are allowed, the suffix is "/module". 2237 * <li>If public and package access are allowed, the suffix is "/package". 2238 * <li>If public, package, and private access are allowed, the suffix is "/private". 2239 * </ul> 2240 * If none of the above cases apply, it is the case that full access 2241 * (public, module, package, private, and protected) is allowed. 2242 * In this case, no suffix is added. 2243 * This is true only of an object obtained originally from 2244 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2245 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2246 * always have restricted access, and will display a suffix. 2247 * <p> 2248 * (It may seem strange that protected access should be 2249 * stronger than private access. Viewed independently from 2250 * package access, protected access is the first to be lost, 2251 * because it requires a direct subclass relationship between 2252 * caller and callee.) 2253 * @see #in 2254 * 2255 * @revised 9 2256 * @spec JPMS 2257 */ 2258 @Override 2259 public String toString() { 2260 String cname = lookupClass.getName(); 2261 if (prevLookupClass != null) 2262 cname += "/" + prevLookupClass.getName(); 2263 switch (allowedModes) { 2264 case 0: // no privileges 2265 return cname + "/noaccess"; 2266 case UNCONDITIONAL: 2267 return cname + "/publicLookup"; 2268 case PUBLIC: 2269 return cname + "/public"; 2270 case PUBLIC|MODULE: 2271 return cname + "/module"; 2272 case PUBLIC|PACKAGE: 2273 case PUBLIC|MODULE|PACKAGE: 2274 return cname + "/package"; 2275 case FULL_POWER_MODES & (~PROTECTED): 2276 case FULL_POWER_MODES & ~(PROTECTED|MODULE): 2277 return cname + "/private"; 2278 case FULL_POWER_MODES: 2279 case FULL_POWER_MODES & (~MODULE): 2280 return cname; 2281 case TRUSTED: 2282 return "/trusted"; // internal only; not exported 2283 default: // Should not happen, but it's a bitfield... 2284 cname = cname + "/" + Integer.toHexString(allowedModes); 2285 assert(false) : cname; 2286 return cname; 2287 } 2288 } 2289 2290 /** 2291 * Produces a method handle for a static method. 2292 * The type of the method handle will be that of the method. 2293 * (Since static methods do not take receivers, there is no 2294 * additional receiver argument inserted into the method handle type, 2295 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2296 * The method and all its argument types must be accessible to the lookup object. 2297 * <p> 2298 * The returned method handle will have 2299 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2300 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2301 * <p> 2302 * If the returned method handle is invoked, the method's class will 2303 * be initialized, if it has not already been initialized. 2304 * <p><b>Example:</b> 2305 * <blockquote><pre>{@code 2306 import static java.lang.invoke.MethodHandles.*; 2307 import static java.lang.invoke.MethodType.*; 2308 ... 2309 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2310 "asList", methodType(List.class, Object[].class)); 2311 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2312 * }</pre></blockquote> 2313 * @param refc the class from which the method is accessed 2314 * @param name the name of the method 2315 * @param type the type of the method 2316 * @return the desired method handle 2317 * @throws NoSuchMethodException if the method does not exist 2318 * @throws IllegalAccessException if access checking fails, 2319 * or if the method is not {@code static}, 2320 * or if the method's variable arity modifier bit 2321 * is set and {@code asVarargsCollector} fails 2322 * @throws SecurityException if a security manager is present and it 2323 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2324 * @throws NullPointerException if any argument is null 2325 */ 2326 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2327 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2328 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2329 } 2330 2331 /** 2332 * Produces a method handle for a virtual method. 2333 * The type of the method handle will be that of the method, 2334 * with the receiver type (usually {@code refc}) prepended. 2335 * The method and all its argument types must be accessible to the lookup object. 2336 * <p> 2337 * When called, the handle will treat the first argument as a receiver 2338 * and, for non-private methods, dispatch on the receiver's type to determine which method 2339 * implementation to enter. 2340 * For private methods the named method in {@code refc} will be invoked on the receiver. 2341 * (The dispatching action is identical with that performed by an 2342 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2343 * <p> 2344 * The first argument will be of type {@code refc} if the lookup 2345 * class has full privileges to access the member. Otherwise 2346 * the member must be {@code protected} and the first argument 2347 * will be restricted in type to the lookup class. 2348 * <p> 2349 * The returned method handle will have 2350 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2351 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2352 * <p> 2353 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2354 * instructions and method handles produced by {@code findVirtual}, 2355 * if the class is {@code MethodHandle} and the name string is 2356 * {@code invokeExact} or {@code invoke}, the resulting 2357 * method handle is equivalent to one produced by 2358 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2359 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2360 * with the same {@code type} argument. 2361 * <p> 2362 * If the class is {@code VarHandle} and the name string corresponds to 2363 * the name of a signature-polymorphic access mode method, the resulting 2364 * method handle is equivalent to one produced by 2365 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2366 * the access mode corresponding to the name string and with the same 2367 * {@code type} arguments. 2368 * <p> 2369 * <b>Example:</b> 2370 * <blockquote><pre>{@code 2371 import static java.lang.invoke.MethodHandles.*; 2372 import static java.lang.invoke.MethodType.*; 2373 ... 2374 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2375 "concat", methodType(String.class, String.class)); 2376 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2377 "hashCode", methodType(int.class)); 2378 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2379 "hashCode", methodType(int.class)); 2380 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2381 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2382 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2383 // interface method: 2384 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2385 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2386 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2387 // constructor "internal method" must be accessed differently: 2388 MethodType MT_newString = methodType(void.class); //()V for new String() 2389 try { assertEquals("impossible", lookup() 2390 .findVirtual(String.class, "<init>", MT_newString)); 2391 } catch (NoSuchMethodException ex) { } // OK 2392 MethodHandle MH_newString = publicLookup() 2393 .findConstructor(String.class, MT_newString); 2394 assertEquals("", (String) MH_newString.invokeExact()); 2395 * }</pre></blockquote> 2396 * 2397 * @param refc the class or interface from which the method is accessed 2398 * @param name the name of the method 2399 * @param type the type of the method, with the receiver argument omitted 2400 * @return the desired method handle 2401 * @throws NoSuchMethodException if the method does not exist 2402 * @throws IllegalAccessException if access checking fails, 2403 * or if the method is {@code static}, 2404 * or if the method's variable arity modifier bit 2405 * is set and {@code asVarargsCollector} fails 2406 * @throws SecurityException if a security manager is present and it 2407 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2408 * @throws NullPointerException if any argument is null 2409 */ 2410 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2411 if (refc == MethodHandle.class) { 2412 MethodHandle mh = findVirtualForMH(name, type); 2413 if (mh != null) return mh; 2414 } else if (refc == VarHandle.class) { 2415 MethodHandle mh = findVirtualForVH(name, type); 2416 if (mh != null) return mh; 2417 } 2418 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2419 MemberName method = resolveOrFail(refKind, refc, name, type); 2420 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2421 } 2422 private MethodHandle findVirtualForMH(String name, MethodType type) { 2423 // these names require special lookups because of the implicit MethodType argument 2424 if ("invoke".equals(name)) 2425 return invoker(type); 2426 if ("invokeExact".equals(name)) 2427 return exactInvoker(type); 2428 assert(!MemberName.isMethodHandleInvokeName(name)); 2429 return null; 2430 } 2431 private MethodHandle findVirtualForVH(String name, MethodType type) { 2432 try { 2433 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2434 } catch (IllegalArgumentException e) { 2435 return null; 2436 } 2437 } 2438 2439 /** 2440 * Produces a method handle which creates an object and initializes it, using 2441 * the constructor of the specified type. 2442 * The parameter types of the method handle will be those of the constructor, 2443 * while the return type will be a reference to the constructor's class. 2444 * The constructor and all its argument types must be accessible to the lookup object. 2445 * <p> 2446 * The requested type must have a return type of {@code void}. 2447 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2448 * <p> 2449 * The returned method handle will have 2450 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2451 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2452 * <p> 2453 * If the returned method handle is invoked, the constructor's class will 2454 * be initialized, if it has not already been initialized. 2455 * <p><b>Example:</b> 2456 * <blockquote><pre>{@code 2457 import static java.lang.invoke.MethodHandles.*; 2458 import static java.lang.invoke.MethodType.*; 2459 ... 2460 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2461 ArrayList.class, methodType(void.class, Collection.class)); 2462 Collection orig = Arrays.asList("x", "y"); 2463 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2464 assert(orig != copy); 2465 assertEquals(orig, copy); 2466 // a variable-arity constructor: 2467 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2468 ProcessBuilder.class, methodType(void.class, String[].class)); 2469 ProcessBuilder pb = (ProcessBuilder) 2470 MH_newProcessBuilder.invoke("x", "y", "z"); 2471 assertEquals("[x, y, z]", pb.command().toString()); 2472 * }</pre></blockquote> 2473 * @param refc the class or interface from which the method is accessed 2474 * @param type the type of the method, with the receiver argument omitted, and a void return type 2475 * @return the desired method handle 2476 * @throws NoSuchMethodException if the constructor does not exist 2477 * @throws IllegalAccessException if access checking fails 2478 * or if the method's variable arity modifier bit 2479 * is set and {@code asVarargsCollector} fails 2480 * @throws SecurityException if a security manager is present and it 2481 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2482 * @throws NullPointerException if any argument is null 2483 */ 2484 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2485 if (refc.isArray()) { 2486 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2487 } 2488 String name = "<init>"; 2489 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2490 return getDirectConstructor(refc, ctor); 2491 } 2492 2493 /** 2494 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2495 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2496 * Such a resolution, as specified in JVMS 5.4.3.1 section, attempts to locate and load the class, 2497 * and then determines whether the class is accessible to this lookup object. 2498 * <p> 2499 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2500 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2501 * 2502 * @param targetName the fully qualified name of the class to be looked up. 2503 * @return the requested class. 2504 * @throws SecurityException if a security manager is present and it 2505 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2506 * @throws LinkageError if the linkage fails 2507 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2508 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2509 * modes. 2510 * @since 9 2511 * @jvms 5.4.3.1 Class and Interface Resolution 2512 */ 2513 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2514 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2515 return accessClass(targetClass); 2516 } 2517 2518 /** 2519 * Determines if a class can be accessed from the lookup context defined by 2520 * this {@code Lookup} object. The static initializer of the class is not run. 2521 * <p> 2522 * If the {@code targetClass} is in the same module as the lookup class, 2523 * the lookup class is {@code LC} in module {@code M1} and 2524 * the previous lookup class is in module {@code M0} or 2525 * {@code null} if not present, 2526 * {@code targetClass} is accessible if and only if one of the following is true: 2527 * <ul> 2528 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2529 * {@code LC} or other class in the same nest of {@code LC}.</li> 2530 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2531 * in the same runtime package of {@code LC}.</li> 2532 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2533 * a public type in {@code M1}.</li> 2534 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2535 * a public type in a package exported by {@code M1} to at least {@code M0} 2536 * if the previous lookup class is present; otherwise, {@code targetClass} 2537 * is a public type in a package exported by {@code M1} unconditionally.</li> 2538 * </ul> 2539 * 2540 * <p> 2541 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2542 * can access public types in all modules when the type is in a package 2543 * that is exported unconditionally. 2544 * <p> 2545 * Otherwise, the target class is in a different module from {@code lookupClass}, 2546 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2547 * is inaccessible. 2548 * <p> 2549 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2550 * {@code M1} is the module containing {@code lookupClass} and 2551 * {@code M2} is the module containing {@code targetClass}, 2552 * then {@code targetClass} is accessible if and only if 2553 * <ul> 2554 * <li>{@code M1} reads {@code M2}, and 2555 * <li>{@code targetClass} is public and in a package exported by 2556 * {@code M2} at least to {@code M1}. 2557 * </ul> 2558 * <p> 2559 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2560 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2561 * containing the previous lookup class, then {@code targetClass} is accessible 2562 * if and only if one of the following is true: 2563 * <ul> 2564 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2565 * {@linkplain Module#reads reads} {@code M0} and the type is 2566 * in a package that is exported to at least {@code M1}. 2567 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2568 * {@linkplain Module#reads reads} {@code M1} and the type is 2569 * in a package that is exported to at least {@code M0}. 2570 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2571 * and {@code M1} reads {@code M2} and the type is in a package 2572 * that is exported to at least both {@code M0} and {@code M2}. 2573 * </ul> 2574 * <p> 2575 * Otherwise, {@code targetClass} is not accessible. 2576 * 2577 * @param targetClass the class to be access-checked 2578 * @return the class that has been access-checked 2579 * @throws IllegalAccessException if the class is not accessible from the lookup class 2580 * and previous lookup class, if present, using the allowed access modes. 2581 * @throws SecurityException if a security manager is present and it 2582 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2583 * @since 9 2584 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2585 */ 2586 public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException { 2587 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2588 throw new MemberName(targetClass).makeAccessException("access violation", this); 2589 } 2590 checkSecurityManager(targetClass, null); 2591 return targetClass; 2592 } 2593 2594 /** 2595 * Produces an early-bound method handle for a virtual method. 2596 * It will bypass checks for overriding methods on the receiver, 2597 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2598 * instruction from within the explicitly specified {@code specialCaller}. 2599 * The type of the method handle will be that of the method, 2600 * with a suitably restricted receiver type prepended. 2601 * (The receiver type will be {@code specialCaller} or a subtype.) 2602 * The method and all its argument types must be accessible 2603 * to the lookup object. 2604 * <p> 2605 * Before method resolution, 2606 * if the explicitly specified caller class is not identical with the 2607 * lookup class, or if this lookup object does not have 2608 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 2609 * privileges, the access fails. 2610 * <p> 2611 * The returned method handle will have 2612 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2613 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2614 * <p style="font-size:smaller;"> 2615 * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API, 2616 * even though the {@code invokespecial} instruction can refer to them 2617 * in special circumstances. Use {@link #findConstructor findConstructor} 2618 * to access instance initialization methods in a safe manner.)</em> 2619 * <p><b>Example:</b> 2620 * <blockquote><pre>{@code 2621 import static java.lang.invoke.MethodHandles.*; 2622 import static java.lang.invoke.MethodType.*; 2623 ... 2624 static class Listie extends ArrayList { 2625 public String toString() { return "[wee Listie]"; } 2626 static Lookup lookup() { return MethodHandles.lookup(); } 2627 } 2628 ... 2629 // no access to constructor via invokeSpecial: 2630 MethodHandle MH_newListie = Listie.lookup() 2631 .findConstructor(Listie.class, methodType(void.class)); 2632 Listie l = (Listie) MH_newListie.invokeExact(); 2633 try { assertEquals("impossible", Listie.lookup().findSpecial( 2634 Listie.class, "<init>", methodType(void.class), Listie.class)); 2635 } catch (NoSuchMethodException ex) { } // OK 2636 // access to super and self methods via invokeSpecial: 2637 MethodHandle MH_super = Listie.lookup().findSpecial( 2638 ArrayList.class, "toString" , methodType(String.class), Listie.class); 2639 MethodHandle MH_this = Listie.lookup().findSpecial( 2640 Listie.class, "toString" , methodType(String.class), Listie.class); 2641 MethodHandle MH_duper = Listie.lookup().findSpecial( 2642 Object.class, "toString" , methodType(String.class), Listie.class); 2643 assertEquals("[]", (String) MH_super.invokeExact(l)); 2644 assertEquals(""+l, (String) MH_this.invokeExact(l)); 2645 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 2646 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 2647 String.class, "toString", methodType(String.class), Listie.class)); 2648 } catch (IllegalAccessException ex) { } // OK 2649 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 2650 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 2651 * }</pre></blockquote> 2652 * 2653 * @param refc the class or interface from which the method is accessed 2654 * @param name the name of the method (which must not be "<init>") 2655 * @param type the type of the method, with the receiver argument omitted 2656 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 2657 * @return the desired method handle 2658 * @throws NoSuchMethodException if the method does not exist 2659 * @throws IllegalAccessException if access checking fails, 2660 * or if the method is {@code static}, 2661 * or if the method's variable arity modifier bit 2662 * is set and {@code asVarargsCollector} fails 2663 * @throws SecurityException if a security manager is present and it 2664 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2665 * @throws NullPointerException if any argument is null 2666 */ 2667 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 2668 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 2669 checkSpecialCaller(specialCaller, refc); 2670 Lookup specialLookup = this.in(specialCaller); 2671 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 2672 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 2673 } 2674 2675 /** 2676 * Produces a method handle giving read access to a non-static field. 2677 * The type of the method handle will have a return type of the field's 2678 * value type. 2679 * The method handle's single argument will be the instance containing 2680 * the field. 2681 * Access checking is performed immediately on behalf of the lookup class. 2682 * @param refc the class or interface from which the method is accessed 2683 * @param name the field's name 2684 * @param type the field's type 2685 * @return a method handle which can load values from the field 2686 * @throws NoSuchFieldException if the field does not exist 2687 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2688 * @throws SecurityException if a security manager is present and it 2689 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2690 * @throws NullPointerException if any argument is null 2691 * @see #findVarHandle(Class, String, Class) 2692 */ 2693 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2694 MemberName field = resolveOrFail(REF_getField, refc, name, type); 2695 return getDirectField(REF_getField, refc, field); 2696 } 2697 2698 /** 2699 * Produces a method handle giving write access to a non-static field. 2700 * The type of the method handle will have a void return type. 2701 * The method handle will take two arguments, the instance containing 2702 * the field, and the value to be stored. 2703 * The second argument will be of the field's value type. 2704 * Access checking is performed immediately on behalf of the lookup class. 2705 * @param refc the class or interface from which the method is accessed 2706 * @param name the field's name 2707 * @param type the field's type 2708 * @return a method handle which can store values into the field 2709 * @throws NoSuchFieldException if the field does not exist 2710 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2711 * or {@code final} 2712 * @throws SecurityException if a security manager is present and it 2713 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2714 * @throws NullPointerException if any argument is null 2715 * @see #findVarHandle(Class, String, Class) 2716 */ 2717 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2718 MemberName field = resolveOrFail(REF_putField, refc, name, type); 2719 return getDirectField(REF_putField, refc, field); 2720 } 2721 2722 /** 2723 * Produces a VarHandle giving access to a non-static field {@code name} 2724 * of type {@code type} declared in a class of type {@code recv}. 2725 * The VarHandle's variable type is {@code type} and it has one 2726 * coordinate type, {@code recv}. 2727 * <p> 2728 * Access checking is performed immediately on behalf of the lookup 2729 * class. 2730 * <p> 2731 * Certain access modes of the returned VarHandle are unsupported under 2732 * the following conditions: 2733 * <ul> 2734 * <li>if the field is declared {@code final}, then the write, atomic 2735 * update, numeric atomic update, and bitwise atomic update access 2736 * modes are unsupported. 2737 * <li>if the field type is anything other than {@code byte}, 2738 * {@code short}, {@code char}, {@code int}, {@code long}, 2739 * {@code float}, or {@code double} then numeric atomic update 2740 * access modes are unsupported. 2741 * <li>if the field type is anything other than {@code boolean}, 2742 * {@code byte}, {@code short}, {@code char}, {@code int} or 2743 * {@code long} then bitwise atomic update access modes are 2744 * unsupported. 2745 * </ul> 2746 * <p> 2747 * If the field is declared {@code volatile} then the returned VarHandle 2748 * will override access to the field (effectively ignore the 2749 * {@code volatile} declaration) in accordance to its specified 2750 * access modes. 2751 * <p> 2752 * If the field type is {@code float} or {@code double} then numeric 2753 * and atomic update access modes compare values using their bitwise 2754 * representation (see {@link Float#floatToRawIntBits} and 2755 * {@link Double#doubleToRawLongBits}, respectively). 2756 * @apiNote 2757 * Bitwise comparison of {@code float} values or {@code double} values, 2758 * as performed by the numeric and atomic update access modes, differ 2759 * from the primitive {@code ==} operator and the {@link Float#equals} 2760 * and {@link Double#equals} methods, specifically with respect to 2761 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 2762 * Care should be taken when performing a compare and set or a compare 2763 * and exchange operation with such values since the operation may 2764 * unexpectedly fail. 2765 * There are many possible NaN values that are considered to be 2766 * {@code NaN} in Java, although no IEEE 754 floating-point operation 2767 * provided by Java can distinguish between them. Operation failure can 2768 * occur if the expected or witness value is a NaN value and it is 2769 * transformed (perhaps in a platform specific manner) into another NaN 2770 * value, and thus has a different bitwise representation (see 2771 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 2772 * details). 2773 * The values {@code -0.0} and {@code +0.0} have different bitwise 2774 * representations but are considered equal when using the primitive 2775 * {@code ==} operator. Operation failure can occur if, for example, a 2776 * numeric algorithm computes an expected value to be say {@code -0.0} 2777 * and previously computed the witness value to be say {@code +0.0}. 2778 * @param recv the receiver class, of type {@code R}, that declares the 2779 * non-static field 2780 * @param name the field's name 2781 * @param type the field's type, of type {@code T} 2782 * @return a VarHandle giving access to non-static fields. 2783 * @throws NoSuchFieldException if the field does not exist 2784 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2785 * @throws SecurityException if a security manager is present and it 2786 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2787 * @throws NullPointerException if any argument is null 2788 * @since 9 2789 */ 2790 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2791 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 2792 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 2793 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 2794 } 2795 2796 /** 2797 * Produces a method handle giving read access to a static field. 2798 * The type of the method handle will have a return type of the field's 2799 * value type. 2800 * The method handle will take no arguments. 2801 * Access checking is performed immediately on behalf of the lookup class. 2802 * <p> 2803 * If the returned method handle is invoked, the field's class will 2804 * be initialized, if it has not already been initialized. 2805 * @param refc the class or interface from which the method is accessed 2806 * @param name the field's name 2807 * @param type the field's type 2808 * @return a method handle which can load values from the field 2809 * @throws NoSuchFieldException if the field does not exist 2810 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 2811 * @throws SecurityException if a security manager is present and it 2812 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2813 * @throws NullPointerException if any argument is null 2814 */ 2815 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2816 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 2817 return getDirectField(REF_getStatic, refc, field); 2818 } 2819 2820 /** 2821 * Produces a method handle giving write access to a static field. 2822 * The type of the method handle will have a void return type. 2823 * The method handle will take a single 2824 * argument, of the field's value type, the value to be stored. 2825 * Access checking is performed immediately on behalf of the lookup class. 2826 * <p> 2827 * If the returned method handle is invoked, the field's class will 2828 * be initialized, if it has not already been initialized. 2829 * @param refc the class or interface from which the method is accessed 2830 * @param name the field's name 2831 * @param type the field's type 2832 * @return a method handle which can store values into the field 2833 * @throws NoSuchFieldException if the field does not exist 2834 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 2835 * or is {@code final} 2836 * @throws SecurityException if a security manager is present and it 2837 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2838 * @throws NullPointerException if any argument is null 2839 */ 2840 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2841 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 2842 return getDirectField(REF_putStatic, refc, field); 2843 } 2844 2845 /** 2846 * Produces a VarHandle giving access to a static field {@code name} of 2847 * type {@code type} declared in a class of type {@code decl}. 2848 * The VarHandle's variable type is {@code type} and it has no 2849 * coordinate types. 2850 * <p> 2851 * Access checking is performed immediately on behalf of the lookup 2852 * class. 2853 * <p> 2854 * If the returned VarHandle is operated on, the declaring class will be 2855 * initialized, if it has not already been initialized. 2856 * <p> 2857 * Certain access modes of the returned VarHandle are unsupported under 2858 * the following conditions: 2859 * <ul> 2860 * <li>if the field is declared {@code final}, then the write, atomic 2861 * update, numeric atomic update, and bitwise atomic update access 2862 * modes are unsupported. 2863 * <li>if the field type is anything other than {@code byte}, 2864 * {@code short}, {@code char}, {@code int}, {@code long}, 2865 * {@code float}, or {@code double}, then numeric atomic update 2866 * access modes are unsupported. 2867 * <li>if the field type is anything other than {@code boolean}, 2868 * {@code byte}, {@code short}, {@code char}, {@code int} or 2869 * {@code long} then bitwise atomic update access modes are 2870 * unsupported. 2871 * </ul> 2872 * <p> 2873 * If the field is declared {@code volatile} then the returned VarHandle 2874 * will override access to the field (effectively ignore the 2875 * {@code volatile} declaration) in accordance to its specified 2876 * access modes. 2877 * <p> 2878 * If the field type is {@code float} or {@code double} then numeric 2879 * and atomic update access modes compare values using their bitwise 2880 * representation (see {@link Float#floatToRawIntBits} and 2881 * {@link Double#doubleToRawLongBits}, respectively). 2882 * @apiNote 2883 * Bitwise comparison of {@code float} values or {@code double} values, 2884 * as performed by the numeric and atomic update access modes, differ 2885 * from the primitive {@code ==} operator and the {@link Float#equals} 2886 * and {@link Double#equals} methods, specifically with respect to 2887 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 2888 * Care should be taken when performing a compare and set or a compare 2889 * and exchange operation with such values since the operation may 2890 * unexpectedly fail. 2891 * There are many possible NaN values that are considered to be 2892 * {@code NaN} in Java, although no IEEE 754 floating-point operation 2893 * provided by Java can distinguish between them. Operation failure can 2894 * occur if the expected or witness value is a NaN value and it is 2895 * transformed (perhaps in a platform specific manner) into another NaN 2896 * value, and thus has a different bitwise representation (see 2897 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 2898 * details). 2899 * The values {@code -0.0} and {@code +0.0} have different bitwise 2900 * representations but are considered equal when using the primitive 2901 * {@code ==} operator. Operation failure can occur if, for example, a 2902 * numeric algorithm computes an expected value to be say {@code -0.0} 2903 * and previously computed the witness value to be say {@code +0.0}. 2904 * @param decl the class that declares the static field 2905 * @param name the field's name 2906 * @param type the field's type, of type {@code T} 2907 * @return a VarHandle giving access to a static field 2908 * @throws NoSuchFieldException if the field does not exist 2909 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 2910 * @throws SecurityException if a security manager is present and it 2911 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2912 * @throws NullPointerException if any argument is null 2913 * @since 9 2914 */ 2915 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2916 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 2917 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 2918 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 2919 } 2920 2921 /** 2922 * Produces an early-bound method handle for a non-static method. 2923 * The receiver must have a supertype {@code defc} in which a method 2924 * of the given name and type is accessible to the lookup class. 2925 * The method and all its argument types must be accessible to the lookup object. 2926 * The type of the method handle will be that of the method, 2927 * without any insertion of an additional receiver parameter. 2928 * The given receiver will be bound into the method handle, 2929 * so that every call to the method handle will invoke the 2930 * requested method on the given receiver. 2931 * <p> 2932 * The returned method handle will have 2933 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2934 * the method's variable arity modifier bit ({@code 0x0080}) is set 2935 * <em>and</em> the trailing array argument is not the only argument. 2936 * (If the trailing array argument is the only argument, 2937 * the given receiver value will be bound to it.) 2938 * <p> 2939 * This is almost equivalent to the following code, with some differences noted below: 2940 * <blockquote><pre>{@code 2941 import static java.lang.invoke.MethodHandles.*; 2942 import static java.lang.invoke.MethodType.*; 2943 ... 2944 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 2945 MethodHandle mh1 = mh0.bindTo(receiver); 2946 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 2947 return mh1; 2948 * }</pre></blockquote> 2949 * where {@code defc} is either {@code receiver.getClass()} or a super 2950 * type of that class, in which the requested method is accessible 2951 * to the lookup class. 2952 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 2953 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 2954 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 2955 * the receiver is restricted by {@code findVirtual} to the lookup class.) 2956 * @param receiver the object from which the method is accessed 2957 * @param name the name of the method 2958 * @param type the type of the method, with the receiver argument omitted 2959 * @return the desired method handle 2960 * @throws NoSuchMethodException if the method does not exist 2961 * @throws IllegalAccessException if access checking fails 2962 * or if the method's variable arity modifier bit 2963 * is set and {@code asVarargsCollector} fails 2964 * @throws SecurityException if a security manager is present and it 2965 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2966 * @throws NullPointerException if any argument is null 2967 * @see MethodHandle#bindTo 2968 * @see #findVirtual 2969 */ 2970 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2971 Class<? extends Object> refc = receiver.getClass(); // may get NPE 2972 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 2973 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 2974 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 2975 throw new IllegalAccessException("The restricted defining class " + 2976 mh.type().leadingReferenceParameter().getName() + 2977 " is not assignable from receiver class " + 2978 receiver.getClass().getName()); 2979 } 2980 return mh.bindArgumentL(0, receiver).setVarargs(method); 2981 } 2982 2983 /** 2984 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 2985 * to <i>m</i>, if the lookup class has permission. 2986 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 2987 * If <i>m</i> is virtual, overriding is respected on every call. 2988 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 2989 * The type of the method handle will be that of the method, 2990 * with the receiver type prepended (but only if it is non-static). 2991 * If the method's {@code accessible} flag is not set, 2992 * access checking is performed immediately on behalf of the lookup class. 2993 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 2994 * <p> 2995 * The returned method handle will have 2996 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2997 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2998 * <p> 2999 * If <i>m</i> is static, and 3000 * if the returned method handle is invoked, the method's class will 3001 * be initialized, if it has not already been initialized. 3002 * @param m the reflected method 3003 * @return a method handle which can invoke the reflected method 3004 * @throws IllegalAccessException if access checking fails 3005 * or if the method's variable arity modifier bit 3006 * is set and {@code asVarargsCollector} fails 3007 * @throws NullPointerException if the argument is null 3008 */ 3009 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3010 if (m.getDeclaringClass() == MethodHandle.class) { 3011 MethodHandle mh = unreflectForMH(m); 3012 if (mh != null) return mh; 3013 } 3014 if (m.getDeclaringClass() == VarHandle.class) { 3015 MethodHandle mh = unreflectForVH(m); 3016 if (mh != null) return mh; 3017 } 3018 MemberName method = new MemberName(m); 3019 byte refKind = method.getReferenceKind(); 3020 if (refKind == REF_invokeSpecial) 3021 refKind = REF_invokeVirtual; 3022 assert(method.isMethod()); 3023 @SuppressWarnings("deprecation") 3024 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3025 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3026 } 3027 private MethodHandle unreflectForMH(Method m) { 3028 // these names require special lookups because they throw UnsupportedOperationException 3029 if (MemberName.isMethodHandleInvokeName(m.getName())) 3030 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3031 return null; 3032 } 3033 private MethodHandle unreflectForVH(Method m) { 3034 // these names require special lookups because they throw UnsupportedOperationException 3035 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3036 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3037 return null; 3038 } 3039 3040 /** 3041 * Produces a method handle for a reflected method. 3042 * It will bypass checks for overriding methods on the receiver, 3043 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3044 * instruction from within the explicitly specified {@code specialCaller}. 3045 * The type of the method handle will be that of the method, 3046 * with a suitably restricted receiver type prepended. 3047 * (The receiver type will be {@code specialCaller} or a subtype.) 3048 * If the method's {@code accessible} flag is not set, 3049 * access checking is performed immediately on behalf of the lookup class, 3050 * as if {@code invokespecial} instruction were being linked. 3051 * <p> 3052 * Before method resolution, 3053 * if the explicitly specified caller class is not identical with the 3054 * lookup class, or if this lookup object does not have 3055 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3056 * privileges, the access fails. 3057 * <p> 3058 * The returned method handle will have 3059 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3060 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3061 * @param m the reflected method 3062 * @param specialCaller the class nominally calling the method 3063 * @return a method handle which can invoke the reflected method 3064 * @throws IllegalAccessException if access checking fails, 3065 * or if the method is {@code static}, 3066 * or if the method's variable arity modifier bit 3067 * is set and {@code asVarargsCollector} fails 3068 * @throws NullPointerException if any argument is null 3069 */ 3070 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3071 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3072 Lookup specialLookup = this.in(specialCaller); 3073 MemberName method = new MemberName(m, true); 3074 assert(method.isMethod()); 3075 // ignore m.isAccessible: this is a new kind of access 3076 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3077 } 3078 3079 /** 3080 * Produces a method handle for a reflected constructor. 3081 * The type of the method handle will be that of the constructor, 3082 * with the return type changed to the declaring class. 3083 * The method handle will perform a {@code newInstance} operation, 3084 * creating a new instance of the constructor's class on the 3085 * arguments passed to the method handle. 3086 * <p> 3087 * If the constructor's {@code accessible} flag is not set, 3088 * access checking is performed immediately on behalf of the lookup class. 3089 * <p> 3090 * The returned method handle will have 3091 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3092 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3093 * <p> 3094 * If the returned method handle is invoked, the constructor's class will 3095 * be initialized, if it has not already been initialized. 3096 * @param c the reflected constructor 3097 * @return a method handle which can invoke the reflected constructor 3098 * @throws IllegalAccessException if access checking fails 3099 * or if the method's variable arity modifier bit 3100 * is set and {@code asVarargsCollector} fails 3101 * @throws NullPointerException if the argument is null 3102 */ 3103 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3104 MemberName ctor = new MemberName(c); 3105 assert(ctor.isConstructor()); 3106 @SuppressWarnings("deprecation") 3107 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3108 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 3109 } 3110 3111 /** 3112 * Produces a method handle giving read access to a reflected field. 3113 * The type of the method handle will have a return type of the field's 3114 * value type. 3115 * If the field is {@code static}, the method handle will take no arguments. 3116 * Otherwise, its single argument will be the instance containing 3117 * the field. 3118 * If the {@code Field} object's {@code accessible} flag is not set, 3119 * access checking is performed immediately on behalf of the lookup class. 3120 * <p> 3121 * If the field is static, and 3122 * if the returned method handle is invoked, the field's class will 3123 * be initialized, if it has not already been initialized. 3124 * @param f the reflected field 3125 * @return a method handle which can load values from the reflected field 3126 * @throws IllegalAccessException if access checking fails 3127 * @throws NullPointerException if the argument is null 3128 */ 3129 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3130 return unreflectField(f, false); 3131 } 3132 3133 /** 3134 * Produces a method handle giving write access to a reflected field. 3135 * The type of the method handle will have a void return type. 3136 * If the field is {@code static}, the method handle will take a single 3137 * argument, of the field's value type, the value to be stored. 3138 * Otherwise, the two arguments will be the instance containing 3139 * the field, and the value to be stored. 3140 * If the {@code Field} object's {@code accessible} flag is not set, 3141 * access checking is performed immediately on behalf of the lookup class. 3142 * <p> 3143 * If the field is {@code final}, write access will not be 3144 * allowed and access checking will fail, except under certain 3145 * narrow circumstances documented for {@link Field#set Field.set}. 3146 * A method handle is returned only if a corresponding call to 3147 * the {@code Field} object's {@code set} method could return 3148 * normally. In particular, fields which are both {@code static} 3149 * and {@code final} may never be set. 3150 * <p> 3151 * If the field is {@code static}, and 3152 * if the returned method handle is invoked, the field's class will 3153 * be initialized, if it has not already been initialized. 3154 * @param f the reflected field 3155 * @return a method handle which can store values into the reflected field 3156 * @throws IllegalAccessException if access checking fails, 3157 * or if the field is {@code final} and write access 3158 * is not enabled on the {@code Field} object 3159 * @throws NullPointerException if the argument is null 3160 */ 3161 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3162 return unreflectField(f, true); 3163 } 3164 3165 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3166 MemberName field = new MemberName(f, isSetter); 3167 if (isSetter && field.isFinal()) { 3168 if (field.isStatic()) { 3169 throw field.makeAccessException("static final field has no write access", this); 3170 } else if (field.getDeclaringClass().isHidden()){ 3171 throw field.makeAccessException("final field in a hidden class has no write access", this); 3172 } 3173 } 3174 assert(isSetter 3175 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3176 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3177 @SuppressWarnings("deprecation") 3178 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3179 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 3180 } 3181 3182 /** 3183 * Produces a VarHandle giving access to a reflected field {@code f} 3184 * of type {@code T} declared in a class of type {@code R}. 3185 * The VarHandle's variable type is {@code T}. 3186 * If the field is non-static the VarHandle has one coordinate type, 3187 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3188 * coordinate types. 3189 * <p> 3190 * Access checking is performed immediately on behalf of the lookup 3191 * class, regardless of the value of the field's {@code accessible} 3192 * flag. 3193 * <p> 3194 * If the field is static, and if the returned VarHandle is operated 3195 * on, the field's declaring class will be initialized, if it has not 3196 * already been initialized. 3197 * <p> 3198 * Certain access modes of the returned VarHandle are unsupported under 3199 * the following conditions: 3200 * <ul> 3201 * <li>if the field is declared {@code final}, then the write, atomic 3202 * update, numeric atomic update, and bitwise atomic update access 3203 * modes are unsupported. 3204 * <li>if the field type is anything other than {@code byte}, 3205 * {@code short}, {@code char}, {@code int}, {@code long}, 3206 * {@code float}, or {@code double} then numeric atomic update 3207 * access modes are unsupported. 3208 * <li>if the field type is anything other than {@code boolean}, 3209 * {@code byte}, {@code short}, {@code char}, {@code int} or 3210 * {@code long} then bitwise atomic update access modes are 3211 * unsupported. 3212 * </ul> 3213 * <p> 3214 * If the field is declared {@code volatile} then the returned VarHandle 3215 * will override access to the field (effectively ignore the 3216 * {@code volatile} declaration) in accordance to its specified 3217 * access modes. 3218 * <p> 3219 * If the field type is {@code float} or {@code double} then numeric 3220 * and atomic update access modes compare values using their bitwise 3221 * representation (see {@link Float#floatToRawIntBits} and 3222 * {@link Double#doubleToRawLongBits}, respectively). 3223 * @apiNote 3224 * Bitwise comparison of {@code float} values or {@code double} values, 3225 * as performed by the numeric and atomic update access modes, differ 3226 * from the primitive {@code ==} operator and the {@link Float#equals} 3227 * and {@link Double#equals} methods, specifically with respect to 3228 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3229 * Care should be taken when performing a compare and set or a compare 3230 * and exchange operation with such values since the operation may 3231 * unexpectedly fail. 3232 * There are many possible NaN values that are considered to be 3233 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3234 * provided by Java can distinguish between them. Operation failure can 3235 * occur if the expected or witness value is a NaN value and it is 3236 * transformed (perhaps in a platform specific manner) into another NaN 3237 * value, and thus has a different bitwise representation (see 3238 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3239 * details). 3240 * The values {@code -0.0} and {@code +0.0} have different bitwise 3241 * representations but are considered equal when using the primitive 3242 * {@code ==} operator. Operation failure can occur if, for example, a 3243 * numeric algorithm computes an expected value to be say {@code -0.0} 3244 * and previously computed the witness value to be say {@code +0.0}. 3245 * @param f the reflected field, with a field of type {@code T}, and 3246 * a declaring class of type {@code R} 3247 * @return a VarHandle giving access to non-static fields or a static 3248 * field 3249 * @throws IllegalAccessException if access checking fails 3250 * @throws NullPointerException if the argument is null 3251 * @since 9 3252 */ 3253 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3254 MemberName getField = new MemberName(f, false); 3255 MemberName putField = new MemberName(f, true); 3256 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 3257 f.getDeclaringClass(), getField, putField); 3258 } 3259 3260 /** 3261 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3262 * created by this lookup object or a similar one. 3263 * Security and access checks are performed to ensure that this lookup object 3264 * is capable of reproducing the target method handle. 3265 * This means that the cracking may fail if target is a direct method handle 3266 * but was created by an unrelated lookup object. 3267 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3268 * and was created by a lookup object for a different class. 3269 * @param target a direct method handle to crack into symbolic reference components 3270 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3271 * @throws SecurityException if a security manager is present and it 3272 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3273 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3274 * @throws NullPointerException if the target is {@code null} 3275 * @see MethodHandleInfo 3276 * @since 1.8 3277 */ 3278 public MethodHandleInfo revealDirect(MethodHandle target) { 3279 MemberName member = target.internalMemberName(); 3280 if (member == null || (!member.isResolved() && 3281 !member.isMethodHandleInvoke() && 3282 !member.isVarHandleMethodInvoke())) 3283 throw newIllegalArgumentException("not a direct method handle"); 3284 Class<?> defc = member.getDeclaringClass(); 3285 byte refKind = member.getReferenceKind(); 3286 assert(MethodHandleNatives.refKindIsValid(refKind)); 3287 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3288 // Devirtualized method invocation is usually formally virtual. 3289 // To avoid creating extra MemberName objects for this common case, 3290 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3291 refKind = REF_invokeVirtual; 3292 if (refKind == REF_invokeVirtual && defc.isInterface()) 3293 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3294 refKind = REF_invokeInterface; 3295 // Check SM permissions and member access before cracking. 3296 try { 3297 checkAccess(refKind, defc, member); 3298 checkSecurityManager(defc, member); 3299 } catch (IllegalAccessException ex) { 3300 throw new IllegalArgumentException(ex); 3301 } 3302 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3303 Class<?> callerClass = target.internalCallerClass(); 3304 if (!hasFullPrivilegeAccess() || callerClass != lookupClass()) 3305 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3306 } 3307 // Produce the handle to the results. 3308 return new InfoFromMemberName(this, member, refKind); 3309 } 3310 3311 /// Helper methods, all package-private. 3312 3313 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3314 checkSymbolicClass(refc); // do this before attempting to resolve 3315 Objects.requireNonNull(name); 3316 Objects.requireNonNull(type); 3317 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 3318 NoSuchFieldException.class); 3319 } 3320 3321 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3322 checkSymbolicClass(refc); // do this before attempting to resolve 3323 Objects.requireNonNull(name); 3324 Objects.requireNonNull(type); 3325 checkMethodName(refKind, name); // NPE check on name 3326 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 3327 NoSuchMethodException.class); 3328 } 3329 3330 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3331 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3332 Objects.requireNonNull(member.getName()); 3333 Objects.requireNonNull(member.getType()); 3334 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), 3335 ReflectiveOperationException.class); 3336 } 3337 3338 MemberName resolveOrNull(byte refKind, MemberName member) { 3339 // do this before attempting to resolve 3340 if (!isClassAccessible(member.getDeclaringClass())) { 3341 return null; 3342 } 3343 Objects.requireNonNull(member.getName()); 3344 Objects.requireNonNull(member.getType()); 3345 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull()); 3346 } 3347 3348 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3349 if (!isClassAccessible(refc)) { 3350 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3351 } 3352 } 3353 3354 boolean isClassAccessible(Class<?> refc) { 3355 Objects.requireNonNull(refc); 3356 Class<?> caller = lookupClassOrNull(); 3357 return caller == null || VerifyAccess.isClassAccessible(refc, caller, prevLookupClass, allowedModes); 3358 } 3359 3360 /** Check name for an illegal leading "<" character. */ 3361 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3362 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3363 throw new NoSuchMethodException("illegal method name: "+name); 3364 } 3365 3366 3367 /** 3368 * Find my trustable caller class if m is a caller sensitive method. 3369 * If this lookup object has full privilege access, then the caller class is the lookupClass. 3370 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3371 */ 3372 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3373 if (MethodHandleNatives.isCallerSensitive(m) && !hasFullPrivilegeAccess()) { 3374 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3375 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3376 } 3377 return this; 3378 } 3379 3380 /** 3381 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3382 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3383 * 3384 * @deprecated This method was originally designed to test {@code PRIVATE} access 3385 * that implies full privilege access but {@code MODULE} access has since become 3386 * independent of {@code PRIVATE} access. It is recommended to call 3387 * {@link #hasFullPrivilegeAccess()} instead. 3388 * @since 9 3389 */ 3390 @Deprecated(since="14") 3391 public boolean hasPrivateAccess() { 3392 return hasFullPrivilegeAccess(); 3393 } 3394 3395 /** 3396 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3397 * i.e. {@code PRIVATE} and {@code MODULE} access. 3398 * A {@code Lookup} object must have full privilege access in order to 3399 * access all members that are allowed to the {@linkplain #lookupClass() lookup class}. 3400 * 3401 * @return {@code true} if this lookup has full privilege access. 3402 * @since 14 3403 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3404 */ 3405 public boolean hasFullPrivilegeAccess() { 3406 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3407 } 3408 3409 /** 3410 * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 3411 * Determines a trustable caller class to compare with refc, the symbolic reference class. 3412 * If this lookup object has full privilege access, then the caller class is the lookupClass. 3413 */ 3414 void checkSecurityManager(Class<?> refc, MemberName m) { 3415 if (allowedModes == TRUSTED) return; 3416 3417 SecurityManager smgr = System.getSecurityManager(); 3418 if (smgr == null) return; 3419 3420 // Step 1: 3421 boolean fullPowerLookup = hasFullPrivilegeAccess(); 3422 if (!fullPowerLookup || 3423 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3424 ReflectUtil.checkPackageAccess(refc); 3425 } 3426 3427 if (m == null) { // findClass or accessClass 3428 // Step 2b: 3429 if (!fullPowerLookup) { 3430 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 3431 } 3432 return; 3433 } 3434 3435 // Step 2a: 3436 if (m.isPublic()) return; 3437 if (!fullPowerLookup) { 3438 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 3439 } 3440 3441 // Step 3: 3442 Class<?> defc = m.getDeclaringClass(); 3443 if (!fullPowerLookup && defc != refc) { 3444 ReflectUtil.checkPackageAccess(defc); 3445 } 3446 } 3447 3448 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3449 boolean wantStatic = (refKind == REF_invokeStatic); 3450 String message; 3451 if (m.isConstructor()) 3452 message = "expected a method, not a constructor"; 3453 else if (!m.isMethod()) 3454 message = "expected a method"; 3455 else if (wantStatic != m.isStatic()) 3456 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3457 else 3458 { checkAccess(refKind, refc, m); return; } 3459 throw m.makeAccessException(message, this); 3460 } 3461 3462 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3463 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3464 String message; 3465 if (wantStatic != m.isStatic()) 3466 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3467 else 3468 { checkAccess(refKind, refc, m); return; } 3469 throw m.makeAccessException(message, this); 3470 } 3471 3472 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3473 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3474 assert(m.referenceKindIsConsistentWith(refKind) && 3475 MethodHandleNatives.refKindIsValid(refKind) && 3476 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3477 int allowedModes = this.allowedModes; 3478 if (allowedModes == TRUSTED) return; 3479 int mods = m.getModifiers(); 3480 if (Modifier.isProtected(mods) && 3481 refKind == REF_invokeVirtual && 3482 m.getDeclaringClass() == Object.class && 3483 m.getName().equals("clone") && 3484 refc.isArray()) { 3485 // The JVM does this hack also. 3486 // (See ClassVerifier::verify_invoke_instructions 3487 // and LinkResolver::check_method_accessability.) 3488 // Because the JVM does not allow separate methods on array types, 3489 // there is no separate method for int[].clone. 3490 // All arrays simply inherit Object.clone. 3491 // But for access checking logic, we make Object.clone 3492 // (normally protected) appear to be public. 3493 // Later on, when the DirectMethodHandle is created, 3494 // its leading argument will be restricted to the 3495 // requested array type. 3496 // N.B. The return type is not adjusted, because 3497 // that is *not* the bytecode behavior. 3498 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3499 } 3500 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3501 // cannot "new" a protected ctor in a different package 3502 mods ^= Modifier.PROTECTED; 3503 } 3504 if (Modifier.isFinal(mods) && 3505 MethodHandleNatives.refKindIsSetter(refKind)) 3506 throw m.makeAccessException("unexpected set of a final field", this); 3507 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3508 if ((requestedModes & allowedModes) != 0) { 3509 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3510 mods, lookupClass(), previousLookupClass(), allowedModes)) 3511 return; 3512 } else { 3513 // Protected members can also be checked as if they were package-private. 3514 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3515 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3516 return; 3517 } 3518 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3519 } 3520 3521 String accessFailedMessage(Class<?> refc, MemberName m) { 3522 Class<?> defc = m.getDeclaringClass(); 3523 int mods = m.getModifiers(); 3524 // check the class first: 3525 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3526 (defc == refc || 3527 Modifier.isPublic(refc.getModifiers()))); 3528 if (!classOK && (allowedModes & PACKAGE) != 0) { 3529 // ignore previous lookup class to check if default package access 3530 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 3531 (defc == refc || 3532 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 3533 } 3534 if (!classOK) 3535 return "class is not public"; 3536 if (Modifier.isPublic(mods)) 3537 return "access to public member failed"; // (how?, module not readable?) 3538 if (Modifier.isPrivate(mods)) 3539 return "member is private"; 3540 if (Modifier.isProtected(mods)) 3541 return "member is protected"; 3542 return "member is private to package"; 3543 } 3544 3545 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 3546 int allowedModes = this.allowedModes; 3547 if (allowedModes == TRUSTED) return; 3548 if ((lookupModes() & PRIVATE) == 0 3549 || (specialCaller != lookupClass() 3550 // ensure non-abstract methods in superinterfaces can be special-invoked 3551 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 3552 throw new MemberName(specialCaller). 3553 makeAccessException("no private access for invokespecial", this); 3554 } 3555 3556 private boolean restrictProtectedReceiver(MemberName method) { 3557 // The accessing class only has the right to use a protected member 3558 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 3559 if (!method.isProtected() || method.isStatic() 3560 || allowedModes == TRUSTED 3561 || method.getDeclaringClass() == lookupClass() 3562 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 3563 return false; 3564 return true; 3565 } 3566 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 3567 assert(!method.isStatic()); 3568 // receiver type of mh is too wide; narrow to caller 3569 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 3570 throw method.makeAccessException("caller class must be a subclass below the method", caller); 3571 } 3572 MethodType rawType = mh.type(); 3573 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 3574 MethodType narrowType = rawType.changeParameterType(0, caller); 3575 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 3576 assert(mh.viewAsTypeChecks(narrowType, true)); 3577 return mh.copyWith(narrowType, mh.form); 3578 } 3579 3580 /** Check access and get the requested method. */ 3581 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3582 final boolean doRestrict = true; 3583 final boolean checkSecurity = true; 3584 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 3585 } 3586 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 3587 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3588 final boolean doRestrict = false; 3589 final boolean checkSecurity = true; 3590 return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup); 3591 } 3592 /** Check access and get the requested method, eliding security manager checks. */ 3593 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3594 final boolean doRestrict = true; 3595 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 3596 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 3597 } 3598 /** Common code for all methods; do not call directly except from immediately above. */ 3599 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 3600 boolean checkSecurity, 3601 boolean doRestrict, 3602 Lookup boundCaller) throws IllegalAccessException { 3603 checkMethod(refKind, refc, method); 3604 // Optionally check with the security manager; this isn't needed for unreflect* calls. 3605 if (checkSecurity) 3606 checkSecurityManager(refc, method); 3607 assert(!method.isMethodHandleInvoke()); 3608 3609 if (refKind == REF_invokeSpecial && 3610 refc != lookupClass() && 3611 !refc.isInterface() && 3612 refc != lookupClass().getSuperclass() && 3613 refc.isAssignableFrom(lookupClass())) { 3614 assert(!method.getName().equals("<init>")); // not this code path 3615 3616 // Per JVMS 6.5, desc. of invokespecial instruction: 3617 // If the method is in a superclass of the LC, 3618 // and if our original search was above LC.super, 3619 // repeat the search (symbolic lookup) from LC.super 3620 // and continue with the direct superclass of that class, 3621 // and so forth, until a match is found or no further superclasses exist. 3622 // FIXME: MemberName.resolve should handle this instead. 3623 Class<?> refcAsSuper = lookupClass(); 3624 MemberName m2; 3625 do { 3626 refcAsSuper = refcAsSuper.getSuperclass(); 3627 m2 = new MemberName(refcAsSuper, 3628 method.getName(), 3629 method.getMethodType(), 3630 REF_invokeSpecial); 3631 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); 3632 } while (m2 == null && // no method is found yet 3633 refc != refcAsSuper); // search up to refc 3634 if (m2 == null) throw new InternalError(method.toString()); 3635 method = m2; 3636 refc = refcAsSuper; 3637 // redo basic checks 3638 checkMethod(refKind, refc, method); 3639 } 3640 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 3641 MethodHandle mh = dmh; 3642 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 3643 if ((doRestrict && refKind == REF_invokeSpecial) || 3644 (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) { 3645 mh = restrictReceiver(method, dmh, lookupClass()); 3646 } 3647 mh = maybeBindCaller(method, mh, boundCaller); 3648 mh = mh.setVarargs(method); 3649 return mh; 3650 } 3651 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 3652 throws IllegalAccessException { 3653 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 3654 return mh; 3655 3656 // boundCaller must have full privilege access. 3657 // It should have been checked by findBoundCallerLookup. Safe to check this again. 3658 if (!boundCaller.hasFullPrivilegeAccess()) 3659 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3660 3661 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 3662 // Note: caller will apply varargs after this step happens. 3663 return cbmh; 3664 } 3665 3666 /** Check access and get the requested field. */ 3667 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3668 final boolean checkSecurity = true; 3669 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 3670 } 3671 /** Check access and get the requested field, eliding security manager checks. */ 3672 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3673 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 3674 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 3675 } 3676 /** Common code for all fields; do not call directly except from immediately above. */ 3677 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 3678 boolean checkSecurity) throws IllegalAccessException { 3679 checkField(refKind, refc, field); 3680 // Optionally check with the security manager; this isn't needed for unreflect* calls. 3681 if (checkSecurity) 3682 checkSecurityManager(refc, field); 3683 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 3684 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 3685 restrictProtectedReceiver(field)); 3686 if (doRestrict) 3687 return restrictReceiver(field, dmh, lookupClass()); 3688 return dmh; 3689 } 3690 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 3691 Class<?> refc, MemberName getField, MemberName putField) 3692 throws IllegalAccessException { 3693 final boolean checkSecurity = true; 3694 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 3695 } 3696 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 3697 Class<?> refc, MemberName getField, MemberName putField) 3698 throws IllegalAccessException { 3699 final boolean checkSecurity = false; 3700 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 3701 } 3702 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 3703 Class<?> refc, MemberName getField, MemberName putField, 3704 boolean checkSecurity) throws IllegalAccessException { 3705 assert getField.isStatic() == putField.isStatic(); 3706 assert getField.isGetter() && putField.isSetter(); 3707 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 3708 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 3709 3710 checkField(getRefKind, refc, getField); 3711 if (checkSecurity) 3712 checkSecurityManager(refc, getField); 3713 3714 if (!putField.isFinal()) { 3715 // A VarHandle does not support updates to final fields, any 3716 // such VarHandle to a final field will be read-only and 3717 // therefore the following write-based accessibility checks are 3718 // only required for non-final fields 3719 checkField(putRefKind, refc, putField); 3720 if (checkSecurity) 3721 checkSecurityManager(refc, putField); 3722 } 3723 3724 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 3725 restrictProtectedReceiver(getField)); 3726 if (doRestrict) { 3727 assert !getField.isStatic(); 3728 // receiver type of VarHandle is too wide; narrow to caller 3729 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 3730 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 3731 } 3732 refc = lookupClass(); 3733 } 3734 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), 3735 this.allowedModes == TRUSTED && !getField.getDeclaringClass().isHidden()); 3736 } 3737 /** Check access and get the requested constructor. */ 3738 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3739 final boolean checkSecurity = true; 3740 return getDirectConstructorCommon(refc, ctor, checkSecurity); 3741 } 3742 /** Check access and get the requested constructor, eliding security manager checks. */ 3743 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3744 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 3745 return getDirectConstructorCommon(refc, ctor, checkSecurity); 3746 } 3747 /** Common code for all constructors; do not call directly except from immediately above. */ 3748 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 3749 boolean checkSecurity) throws IllegalAccessException { 3750 assert(ctor.isConstructor()); 3751 checkAccess(REF_newInvokeSpecial, refc, ctor); 3752 // Optionally check with the security manager; this isn't needed for unreflect* calls. 3753 if (checkSecurity) 3754 checkSecurityManager(refc, ctor); 3755 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3756 return DirectMethodHandle.make(ctor).setVarargs(ctor); 3757 } 3758 3759 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 3760 */ 3761 /*non-public*/ 3762 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 3763 throws ReflectiveOperationException { 3764 if (!(type instanceof Class || type instanceof MethodType)) 3765 throw new InternalError("unresolved MemberName"); 3766 MemberName member = new MemberName(refKind, defc, name, type); 3767 MethodHandle mh = LOOKASIDE_TABLE.get(member); 3768 if (mh != null) { 3769 checkSymbolicClass(defc); 3770 return mh; 3771 } 3772 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 3773 // Treat MethodHandle.invoke and invokeExact specially. 3774 mh = findVirtualForMH(member.getName(), member.getMethodType()); 3775 if (mh != null) { 3776 return mh; 3777 } 3778 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 3779 // Treat signature-polymorphic methods on VarHandle specially. 3780 mh = findVirtualForVH(member.getName(), member.getMethodType()); 3781 if (mh != null) { 3782 return mh; 3783 } 3784 } 3785 MemberName resolved = resolveOrFail(refKind, member); 3786 mh = getDirectMethodForConstant(refKind, defc, resolved); 3787 if (mh instanceof DirectMethodHandle 3788 && canBeCached(refKind, defc, resolved)) { 3789 MemberName key = mh.internalMemberName(); 3790 if (key != null) { 3791 key = key.asNormalOriginal(); 3792 } 3793 if (member.equals(key)) { // better safe than sorry 3794 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 3795 } 3796 } 3797 return mh; 3798 } 3799 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 3800 if (refKind == REF_invokeSpecial) { 3801 return false; 3802 } 3803 if (!Modifier.isPublic(defc.getModifiers()) || 3804 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 3805 !member.isPublic() || 3806 member.isCallerSensitive()) { 3807 return false; 3808 } 3809 ClassLoader loader = defc.getClassLoader(); 3810 if (loader != null) { 3811 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 3812 boolean found = false; 3813 while (sysl != null) { 3814 if (loader == sysl) { found = true; break; } 3815 sysl = sysl.getParent(); 3816 } 3817 if (!found) { 3818 return false; 3819 } 3820 } 3821 try { 3822 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 3823 new MemberName(refKind, defc, member.getName(), member.getType())); 3824 if (resolved2 == null) { 3825 return false; 3826 } 3827 checkSecurityManager(defc, resolved2); 3828 } catch (SecurityException ex) { 3829 return false; 3830 } 3831 return true; 3832 } 3833 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 3834 throws ReflectiveOperationException { 3835 if (MethodHandleNatives.refKindIsField(refKind)) { 3836 return getDirectFieldNoSecurityManager(refKind, defc, member); 3837 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 3838 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member)); 3839 } else if (refKind == REF_newInvokeSpecial) { 3840 return getDirectConstructorNoSecurityManager(defc, member); 3841 } 3842 // oops 3843 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 3844 } 3845 3846 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 3847 } 3848 3849 /** 3850 * Produces a method handle constructing arrays of a desired type, 3851 * as if by the {@code anewarray} bytecode. 3852 * The return type of the method handle will be the array type. 3853 * The type of its sole argument will be {@code int}, which specifies the size of the array. 3854 * 3855 * <p> If the returned method handle is invoked with a negative 3856 * array size, a {@code NegativeArraySizeException} will be thrown. 3857 * 3858 * @param arrayClass an array type 3859 * @return a method handle which can create arrays of the given type 3860 * @throws NullPointerException if the argument is {@code null} 3861 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 3862 * @see java.lang.reflect.Array#newInstance(Class, int) 3863 * @jvms 6.5 {@code anewarray} Instruction 3864 * @since 9 3865 */ 3866 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 3867 if (!arrayClass.isArray()) { 3868 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 3869 } 3870 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 3871 bindTo(arrayClass.getComponentType()); 3872 return ani.asType(ani.type().changeReturnType(arrayClass)); 3873 } 3874 3875 /** 3876 * Produces a method handle returning the length of an array, 3877 * as if by the {@code arraylength} bytecode. 3878 * The type of the method handle will have {@code int} as return type, 3879 * and its sole argument will be the array type. 3880 * 3881 * <p> If the returned method handle is invoked with a {@code null} 3882 * array reference, a {@code NullPointerException} will be thrown. 3883 * 3884 * @param arrayClass an array type 3885 * @return a method handle which can retrieve the length of an array of the given array type 3886 * @throws NullPointerException if the argument is {@code null} 3887 * @throws IllegalArgumentException if arrayClass is not an array type 3888 * @jvms 6.5 {@code arraylength} Instruction 3889 * @since 9 3890 */ 3891 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 3892 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 3893 } 3894 3895 /** 3896 * Produces a method handle giving read access to elements of an array, 3897 * as if by the {@code aaload} bytecode. 3898 * The type of the method handle will have a return type of the array's 3899 * element type. Its first argument will be the array type, 3900 * and the second will be {@code int}. 3901 * 3902 * <p> When the returned method handle is invoked, 3903 * the array reference and array index are checked. 3904 * A {@code NullPointerException} will be thrown if the array reference 3905 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 3906 * thrown if the index is negative or if it is greater than or equal to 3907 * the length of the array. 3908 * 3909 * @param arrayClass an array type 3910 * @return a method handle which can load values from the given array type 3911 * @throws NullPointerException if the argument is null 3912 * @throws IllegalArgumentException if arrayClass is not an array type 3913 * @jvms 6.5 {@code aaload} Instruction 3914 */ 3915 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 3916 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 3917 } 3918 3919 /** 3920 * Produces a method handle giving write access to elements of an array, 3921 * as if by the {@code astore} bytecode. 3922 * The type of the method handle will have a void return type. 3923 * Its last argument will be the array's element type. 3924 * The first and second arguments will be the array type and int. 3925 * 3926 * <p> When the returned method handle is invoked, 3927 * the array reference and array index are checked. 3928 * A {@code NullPointerException} will be thrown if the array reference 3929 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 3930 * thrown if the index is negative or if it is greater than or equal to 3931 * the length of the array. 3932 * 3933 * @param arrayClass the class of an array 3934 * @return a method handle which can store values into the array type 3935 * @throws NullPointerException if the argument is null 3936 * @throws IllegalArgumentException if arrayClass is not an array type 3937 * @jvms 6.5 {@code aastore} Instruction 3938 */ 3939 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 3940 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 3941 } 3942 3943 /** 3944 * Produces a VarHandle giving access to elements of an array of type 3945 * {@code arrayClass}. The VarHandle's variable type is the component type 3946 * of {@code arrayClass} and the list of coordinate types is 3947 * {@code (arrayClass, int)}, where the {@code int} coordinate type 3948 * corresponds to an argument that is an index into an array. 3949 * <p> 3950 * Certain access modes of the returned VarHandle are unsupported under 3951 * the following conditions: 3952 * <ul> 3953 * <li>if the component type is anything other than {@code byte}, 3954 * {@code short}, {@code char}, {@code int}, {@code long}, 3955 * {@code float}, or {@code double} then numeric atomic update access 3956 * modes are unsupported. 3957 * <li>if the field type is anything other than {@code boolean}, 3958 * {@code byte}, {@code short}, {@code char}, {@code int} or 3959 * {@code long} then bitwise atomic update access modes are 3960 * unsupported. 3961 * </ul> 3962 * <p> 3963 * If the component type is {@code float} or {@code double} then numeric 3964 * and atomic update access modes compare values using their bitwise 3965 * representation (see {@link Float#floatToRawIntBits} and 3966 * {@link Double#doubleToRawLongBits}, respectively). 3967 * 3968 * <p> When the returned {@code VarHandle} is invoked, 3969 * the array reference and array index are checked. 3970 * A {@code NullPointerException} will be thrown if the array reference 3971 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 3972 * thrown if the index is negative or if it is greater than or equal to 3973 * the length of the array. 3974 * 3975 * @apiNote 3976 * Bitwise comparison of {@code float} values or {@code double} values, 3977 * as performed by the numeric and atomic update access modes, differ 3978 * from the primitive {@code ==} operator and the {@link Float#equals} 3979 * and {@link Double#equals} methods, specifically with respect to 3980 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3981 * Care should be taken when performing a compare and set or a compare 3982 * and exchange operation with such values since the operation may 3983 * unexpectedly fail. 3984 * There are many possible NaN values that are considered to be 3985 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3986 * provided by Java can distinguish between them. Operation failure can 3987 * occur if the expected or witness value is a NaN value and it is 3988 * transformed (perhaps in a platform specific manner) into another NaN 3989 * value, and thus has a different bitwise representation (see 3990 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3991 * details). 3992 * The values {@code -0.0} and {@code +0.0} have different bitwise 3993 * representations but are considered equal when using the primitive 3994 * {@code ==} operator. Operation failure can occur if, for example, a 3995 * numeric algorithm computes an expected value to be say {@code -0.0} 3996 * and previously computed the witness value to be say {@code +0.0}. 3997 * @param arrayClass the class of an array, of type {@code T[]} 3998 * @return a VarHandle giving access to elements of an array 3999 * @throws NullPointerException if the arrayClass is null 4000 * @throws IllegalArgumentException if arrayClass is not an array type 4001 * @since 9 4002 */ 4003 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4004 return VarHandles.makeArrayElementHandle(arrayClass); 4005 } 4006 4007 /** 4008 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4009 * viewed as if it were a different primitive array type, such as 4010 * {@code int[]} or {@code long[]}. 4011 * The VarHandle's variable type is the component type of 4012 * {@code viewArrayClass} and the list of coordinate types is 4013 * {@code (byte[], int)}, where the {@code int} coordinate type 4014 * corresponds to an argument that is an index into a {@code byte[]} array. 4015 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4016 * array, composing bytes to or from a value of the component type of 4017 * {@code viewArrayClass} according to the given endianness. 4018 * <p> 4019 * The supported component types (variables types) are {@code short}, 4020 * {@code char}, {@code int}, {@code long}, {@code float} and 4021 * {@code double}. 4022 * <p> 4023 * Access of bytes at a given index will result in an 4024 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4025 * or greater than the {@code byte[]} array length minus the size (in bytes) 4026 * of {@code T}. 4027 * <p> 4028 * Access of bytes at an index may be aligned or misaligned for {@code T}, 4029 * with respect to the underlying memory address, {@code A} say, associated 4030 * with the array and index. 4031 * If access is misaligned then access for anything other than the 4032 * {@code get} and {@code set} access modes will result in an 4033 * {@code IllegalStateException}. In such cases atomic access is only 4034 * guaranteed with respect to the largest power of two that divides the GCD 4035 * of {@code A} and the size (in bytes) of {@code T}. 4036 * If access is aligned then following access modes are supported and are 4037 * guaranteed to support atomic access: 4038 * <ul> 4039 * <li>read write access modes for all {@code T}, with the exception of 4040 * access modes {@code get} and {@code set} for {@code long} and 4041 * {@code double} on 32-bit platforms. 4042 * <li>atomic update access modes for {@code int}, {@code long}, 4043 * {@code float} or {@code double}. 4044 * (Future major platform releases of the JDK may support additional 4045 * types for certain currently unsupported access modes.) 4046 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4047 * (Future major platform releases of the JDK may support additional 4048 * numeric types for certain currently unsupported access modes.) 4049 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4050 * (Future major platform releases of the JDK may support additional 4051 * numeric types for certain currently unsupported access modes.) 4052 * </ul> 4053 * <p> 4054 * Misaligned access, and therefore atomicity guarantees, may be determined 4055 * for {@code byte[]} arrays without operating on a specific array. Given 4056 * an {@code index}, {@code T} and it's corresponding boxed type, 4057 * {@code T_BOX}, misalignment may be determined as follows: 4058 * <pre>{@code 4059 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4060 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 4061 * alignmentOffset(0, sizeOfT); 4062 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 4063 * boolean isMisaligned = misalignedAtIndex != 0; 4064 * }</pre> 4065 * <p> 4066 * If the variable type is {@code float} or {@code double} then atomic 4067 * update access modes compare values using their bitwise representation 4068 * (see {@link Float#floatToRawIntBits} and 4069 * {@link Double#doubleToRawLongBits}, respectively). 4070 * @param viewArrayClass the view array class, with a component type of 4071 * type {@code T} 4072 * @param byteOrder the endianness of the view array elements, as 4073 * stored in the underlying {@code byte} array 4074 * @return a VarHandle giving access to elements of a {@code byte[]} array 4075 * viewed as if elements corresponding to the components type of the view 4076 * array class 4077 * @throws NullPointerException if viewArrayClass or byteOrder is null 4078 * @throws IllegalArgumentException if viewArrayClass is not an array type 4079 * @throws UnsupportedOperationException if the component type of 4080 * viewArrayClass is not supported as a variable type 4081 * @since 9 4082 */ 4083 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4084 ByteOrder byteOrder) throws IllegalArgumentException { 4085 Objects.requireNonNull(byteOrder); 4086 return VarHandles.byteArrayViewHandle(viewArrayClass, 4087 byteOrder == ByteOrder.BIG_ENDIAN); 4088 } 4089 4090 /** 4091 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4092 * viewed as if it were an array of elements of a different primitive 4093 * component type to that of {@code byte}, such as {@code int[]} or 4094 * {@code long[]}. 4095 * The VarHandle's variable type is the component type of 4096 * {@code viewArrayClass} and the list of coordinate types is 4097 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4098 * corresponds to an argument that is an index into a {@code byte[]} array. 4099 * The returned VarHandle accesses bytes at an index in a 4100 * {@code ByteBuffer}, composing bytes to or from a value of the component 4101 * type of {@code viewArrayClass} according to the given endianness. 4102 * <p> 4103 * The supported component types (variables types) are {@code short}, 4104 * {@code char}, {@code int}, {@code long}, {@code float} and 4105 * {@code double}. 4106 * <p> 4107 * Access will result in a {@code ReadOnlyBufferException} for anything 4108 * other than the read access modes if the {@code ByteBuffer} is read-only. 4109 * <p> 4110 * Access of bytes at a given index will result in an 4111 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4112 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4113 * {@code T}. 4114 * <p> 4115 * Access of bytes at an index may be aligned or misaligned for {@code T}, 4116 * with respect to the underlying memory address, {@code A} say, associated 4117 * with the {@code ByteBuffer} and index. 4118 * If access is misaligned then access for anything other than the 4119 * {@code get} and {@code set} access modes will result in an 4120 * {@code IllegalStateException}. In such cases atomic access is only 4121 * guaranteed with respect to the largest power of two that divides the GCD 4122 * of {@code A} and the size (in bytes) of {@code T}. 4123 * If access is aligned then following access modes are supported and are 4124 * guaranteed to support atomic access: 4125 * <ul> 4126 * <li>read write access modes for all {@code T}, with the exception of 4127 * access modes {@code get} and {@code set} for {@code long} and 4128 * {@code double} on 32-bit platforms. 4129 * <li>atomic update access modes for {@code int}, {@code long}, 4130 * {@code float} or {@code double}. 4131 * (Future major platform releases of the JDK may support additional 4132 * types for certain currently unsupported access modes.) 4133 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4134 * (Future major platform releases of the JDK may support additional 4135 * numeric types for certain currently unsupported access modes.) 4136 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4137 * (Future major platform releases of the JDK may support additional 4138 * numeric types for certain currently unsupported access modes.) 4139 * </ul> 4140 * <p> 4141 * Misaligned access, and therefore atomicity guarantees, may be determined 4142 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4143 * {@code index}, {@code T} and it's corresponding boxed type, 4144 * {@code T_BOX}, as follows: 4145 * <pre>{@code 4146 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4147 * ByteBuffer bb = ... 4148 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4149 * boolean isMisaligned = misalignedAtIndex != 0; 4150 * }</pre> 4151 * <p> 4152 * If the variable type is {@code float} or {@code double} then atomic 4153 * update access modes compare values using their bitwise representation 4154 * (see {@link Float#floatToRawIntBits} and 4155 * {@link Double#doubleToRawLongBits}, respectively). 4156 * @param viewArrayClass the view array class, with a component type of 4157 * type {@code T} 4158 * @param byteOrder the endianness of the view array elements, as 4159 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4160 * endianness of a {@code ByteBuffer}) 4161 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4162 * viewed as if elements corresponding to the components type of the view 4163 * array class 4164 * @throws NullPointerException if viewArrayClass or byteOrder is null 4165 * @throws IllegalArgumentException if viewArrayClass is not an array type 4166 * @throws UnsupportedOperationException if the component type of 4167 * viewArrayClass is not supported as a variable type 4168 * @since 9 4169 */ 4170 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4171 ByteOrder byteOrder) throws IllegalArgumentException { 4172 Objects.requireNonNull(byteOrder); 4173 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4174 byteOrder == ByteOrder.BIG_ENDIAN); 4175 } 4176 4177 4178 /// method handle invocation (reflective style) 4179 4180 /** 4181 * Produces a method handle which will invoke any method handle of the 4182 * given {@code type}, with a given number of trailing arguments replaced by 4183 * a single trailing {@code Object[]} array. 4184 * The resulting invoker will be a method handle with the following 4185 * arguments: 4186 * <ul> 4187 * <li>a single {@code MethodHandle} target 4188 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4189 * <li>an {@code Object[]} array containing trailing arguments 4190 * </ul> 4191 * <p> 4192 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4193 * the indicated {@code type}. 4194 * That is, if the target is exactly of the given {@code type}, it will behave 4195 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4196 * is used to convert the target to the required {@code type}. 4197 * <p> 4198 * The type of the returned invoker will not be the given {@code type}, but rather 4199 * will have all parameters except the first {@code leadingArgCount} 4200 * replaced by a single array of type {@code Object[]}, which will be 4201 * the final parameter. 4202 * <p> 4203 * Before invoking its target, the invoker will spread the final array, apply 4204 * reference casts as necessary, and unbox and widen primitive arguments. 4205 * If, when the invoker is called, the supplied array argument does 4206 * not have the correct number of elements, the invoker will throw 4207 * an {@link IllegalArgumentException} instead of invoking the target. 4208 * <p> 4209 * This method is equivalent to the following code (though it may be more efficient): 4210 * <blockquote><pre>{@code 4211 MethodHandle invoker = MethodHandles.invoker(type); 4212 int spreadArgCount = type.parameterCount() - leadingArgCount; 4213 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4214 return invoker; 4215 * }</pre></blockquote> 4216 * This method throws no reflective or security exceptions. 4217 * @param type the desired target type 4218 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4219 * @return a method handle suitable for invoking any method handle of the given type 4220 * @throws NullPointerException if {@code type} is null 4221 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4222 * the range from 0 to {@code type.parameterCount()} inclusive, 4223 * or if the resulting method handle's type would have 4224 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4225 */ 4226 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4227 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4228 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4229 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4230 return type.invokers().spreadInvoker(leadingArgCount); 4231 } 4232 4233 /** 4234 * Produces a special <em>invoker method handle</em> which can be used to 4235 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4236 * The resulting invoker will have a type which is 4237 * exactly equal to the desired type, except that it will accept 4238 * an additional leading argument of type {@code MethodHandle}. 4239 * <p> 4240 * This method is equivalent to the following code (though it may be more efficient): 4241 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4242 * 4243 * <p style="font-size:smaller;"> 4244 * <em>Discussion:</em> 4245 * Invoker method handles can be useful when working with variable method handles 4246 * of unknown types. 4247 * For example, to emulate an {@code invokeExact} call to a variable method 4248 * handle {@code M}, extract its type {@code T}, 4249 * look up the invoker method {@code X} for {@code T}, 4250 * and call the invoker method, as {@code X.invoke(T, A...)}. 4251 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4252 * is unknown.) 4253 * If spreading, collecting, or other argument transformations are required, 4254 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4255 * method handle values, as long as they are compatible with the type of {@code X}. 4256 * <p style="font-size:smaller;"> 4257 * <em>(Note: The invoker method is not available via the Core Reflection API. 4258 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4259 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4260 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4261 * <p> 4262 * This method throws no reflective or security exceptions. 4263 * @param type the desired target type 4264 * @return a method handle suitable for invoking any method handle of the given type 4265 * @throws IllegalArgumentException if the resulting method handle's type would have 4266 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4267 */ 4268 public static MethodHandle exactInvoker(MethodType type) { 4269 return type.invokers().exactInvoker(); 4270 } 4271 4272 /** 4273 * Produces a special <em>invoker method handle</em> which can be used to 4274 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4275 * The resulting invoker will have a type which is 4276 * exactly equal to the desired type, except that it will accept 4277 * an additional leading argument of type {@code MethodHandle}. 4278 * <p> 4279 * Before invoking its target, if the target differs from the expected type, 4280 * the invoker will apply reference casts as 4281 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4282 * Similarly, the return value will be converted as necessary. 4283 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4284 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4285 * <p> 4286 * This method is equivalent to the following code (though it may be more efficient): 4287 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4288 * <p style="font-size:smaller;"> 4289 * <em>Discussion:</em> 4290 * A {@linkplain MethodType#genericMethodType general method type} is one which 4291 * mentions only {@code Object} arguments and return values. 4292 * An invoker for such a type is capable of calling any method handle 4293 * of the same arity as the general type. 4294 * <p style="font-size:smaller;"> 4295 * <em>(Note: The invoker method is not available via the Core Reflection API. 4296 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4297 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4298 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4299 * <p> 4300 * This method throws no reflective or security exceptions. 4301 * @param type the desired target type 4302 * @return a method handle suitable for invoking any method handle convertible to the given type 4303 * @throws IllegalArgumentException if the resulting method handle's type would have 4304 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4305 */ 4306 public static MethodHandle invoker(MethodType type) { 4307 return type.invokers().genericInvoker(); 4308 } 4309 4310 /** 4311 * Produces a special <em>invoker method handle</em> which can be used to 4312 * invoke a signature-polymorphic access mode method on any VarHandle whose 4313 * associated access mode type is compatible with the given type. 4314 * The resulting invoker will have a type which is exactly equal to the 4315 * desired given type, except that it will accept an additional leading 4316 * argument of type {@code VarHandle}. 4317 * 4318 * @param accessMode the VarHandle access mode 4319 * @param type the desired target type 4320 * @return a method handle suitable for invoking an access mode method of 4321 * any VarHandle whose access mode type is of the given type. 4322 * @since 9 4323 */ 4324 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4325 return type.invokers().varHandleMethodExactInvoker(accessMode); 4326 } 4327 4328 /** 4329 * Produces a special <em>invoker method handle</em> which can be used to 4330 * invoke a signature-polymorphic access mode method on any VarHandle whose 4331 * associated access mode type is compatible with the given type. 4332 * The resulting invoker will have a type which is exactly equal to the 4333 * desired given type, except that it will accept an additional leading 4334 * argument of type {@code VarHandle}. 4335 * <p> 4336 * Before invoking its target, if the access mode type differs from the 4337 * desired given type, the invoker will apply reference casts as necessary 4338 * and box, unbox, or widen primitive values, as if by 4339 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4340 * converted as necessary. 4341 * <p> 4342 * This method is equivalent to the following code (though it may be more 4343 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4344 * 4345 * @param accessMode the VarHandle access mode 4346 * @param type the desired target type 4347 * @return a method handle suitable for invoking an access mode method of 4348 * any VarHandle whose access mode type is convertible to the given 4349 * type. 4350 * @since 9 4351 */ 4352 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4353 return type.invokers().varHandleMethodInvoker(accessMode); 4354 } 4355 4356 /*non-public*/ 4357 static MethodHandle basicInvoker(MethodType type) { 4358 return type.invokers().basicInvoker(); 4359 } 4360 4361 /// method handle modification (creation from other method handles) 4362 4363 /** 4364 * Produces a method handle which adapts the type of the 4365 * given method handle to a new type by pairwise argument and return type conversion. 4366 * The original type and new type must have the same number of arguments. 4367 * The resulting method handle is guaranteed to report a type 4368 * which is equal to the desired new type. 4369 * <p> 4370 * If the original type and new type are equal, returns target. 4371 * <p> 4372 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4373 * and some additional conversions are also applied if those conversions fail. 4374 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4375 * if possible, before or instead of any conversions done by {@code asType}: 4376 * <ul> 4377 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4378 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4379 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4380 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4381 * the boolean is converted to a byte value, 1 for true, 0 for false. 4382 * (This treatment follows the usage of the bytecode verifier.) 4383 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4384 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 4385 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4386 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4387 * then a Java casting conversion (JLS 5.5) is applied. 4388 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4389 * widening and/or narrowing.) 4390 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4391 * conversion will be applied at runtime, possibly followed 4392 * by a Java casting conversion (JLS 5.5) on the primitive value, 4393 * possibly followed by a conversion from byte to boolean by testing 4394 * the low-order bit. 4395 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4396 * and if the reference is null at runtime, a zero value is introduced. 4397 * </ul> 4398 * @param target the method handle to invoke after arguments are retyped 4399 * @param newType the expected type of the new method handle 4400 * @return a method handle which delegates to the target after performing 4401 * any necessary argument conversions, and arranges for any 4402 * necessary return value conversions 4403 * @throws NullPointerException if either argument is null 4404 * @throws WrongMethodTypeException if the conversion cannot be made 4405 * @see MethodHandle#asType 4406 */ 4407 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4408 explicitCastArgumentsChecks(target, newType); 4409 // use the asTypeCache when possible: 4410 MethodType oldType = target.type(); 4411 if (oldType == newType) return target; 4412 if (oldType.explicitCastEquivalentToAsType(newType)) { 4413 return target.asFixedArity().asType(newType); 4414 } 4415 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4416 } 4417 4418 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4419 if (target.type().parameterCount() != newType.parameterCount()) { 4420 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4421 } 4422 } 4423 4424 /** 4425 * Produces a method handle which adapts the calling sequence of the 4426 * given method handle to a new type, by reordering the arguments. 4427 * The resulting method handle is guaranteed to report a type 4428 * which is equal to the desired new type. 4429 * <p> 4430 * The given array controls the reordering. 4431 * Call {@code #I} the number of incoming parameters (the value 4432 * {@code newType.parameterCount()}, and call {@code #O} the number 4433 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4434 * Then the length of the reordering array must be {@code #O}, 4435 * and each element must be a non-negative number less than {@code #I}. 4436 * For every {@code N} less than {@code #O}, the {@code N}-th 4437 * outgoing argument will be taken from the {@code I}-th incoming 4438 * argument, where {@code I} is {@code reorder[N]}. 4439 * <p> 4440 * No argument or return value conversions are applied. 4441 * The type of each incoming argument, as determined by {@code newType}, 4442 * must be identical to the type of the corresponding outgoing parameter 4443 * or parameters in the target method handle. 4444 * The return type of {@code newType} must be identical to the return 4445 * type of the original target. 4446 * <p> 4447 * The reordering array need not specify an actual permutation. 4448 * An incoming argument will be duplicated if its index appears 4449 * more than once in the array, and an incoming argument will be dropped 4450 * if its index does not appear in the array. 4451 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4452 * incoming arguments which are not mentioned in the reordering array 4453 * may be of any type, as determined only by {@code newType}. 4454 * <blockquote><pre>{@code 4455 import static java.lang.invoke.MethodHandles.*; 4456 import static java.lang.invoke.MethodType.*; 4457 ... 4458 MethodType intfn1 = methodType(int.class, int.class); 4459 MethodType intfn2 = methodType(int.class, int.class, int.class); 4460 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4461 assert(sub.type().equals(intfn2)); 4462 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4463 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4464 assert((int)rsub.invokeExact(1, 100) == 99); 4465 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4466 assert(add.type().equals(intfn2)); 4467 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4468 assert(twice.type().equals(intfn1)); 4469 assert((int)twice.invokeExact(21) == 42); 4470 * }</pre></blockquote> 4471 * <p> 4472 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4473 * variable-arity method handle}, even if the original target method handle was. 4474 * @param target the method handle to invoke after arguments are reordered 4475 * @param newType the expected type of the new method handle 4476 * @param reorder an index array which controls the reordering 4477 * @return a method handle which delegates to the target after it 4478 * drops unused arguments and moves and/or duplicates the other arguments 4479 * @throws NullPointerException if any argument is null 4480 * @throws IllegalArgumentException if the index array length is not equal to 4481 * the arity of the target, or if any index array element 4482 * not a valid index for a parameter of {@code newType}, 4483 * or if two corresponding parameter types in 4484 * {@code target.type()} and {@code newType} are not identical, 4485 */ 4486 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4487 reorder = reorder.clone(); // get a private copy 4488 MethodType oldType = target.type(); 4489 permuteArgumentChecks(reorder, newType, oldType); 4490 // first detect dropped arguments and handle them separately 4491 int[] originalReorder = reorder; 4492 BoundMethodHandle result = target.rebind(); 4493 LambdaForm form = result.form; 4494 int newArity = newType.parameterCount(); 4495 // Normalize the reordering into a real permutation, 4496 // by removing duplicates and adding dropped elements. 4497 // This somewhat improves lambda form caching, as well 4498 // as simplifying the transform by breaking it up into steps. 4499 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4500 if (ddIdx > 0) { 4501 // We found a duplicated entry at reorder[ddIdx]. 4502 // Example: (x,y,z)->asList(x,y,z) 4503 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4504 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4505 // The starred element corresponds to the argument 4506 // deleted by the dupArgumentForm transform. 4507 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4508 boolean killFirst = false; 4509 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4510 // Set killFirst if the dup is larger than an intervening position. 4511 // This will remove at least one inversion from the permutation. 4512 if (dupVal > val) killFirst = true; 4513 } 4514 if (!killFirst) { 4515 srcPos = dstPos; 4516 dstPos = ddIdx; 4517 } 4518 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4519 assert (reorder[srcPos] == reorder[dstPos]); 4520 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4521 // contract the reordering by removing the element at dstPos 4522 int tailPos = dstPos + 1; 4523 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4524 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4525 } else { 4526 int dropVal = ~ddIdx, insPos = 0; 4527 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4528 // Find first element of reorder larger than dropVal. 4529 // This is where we will insert the dropVal. 4530 insPos += 1; 4531 } 4532 Class<?> ptype = newType.parameterType(dropVal); 4533 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4534 oldType = oldType.insertParameterTypes(insPos, ptype); 4535 // expand the reordering by inserting an element at insPos 4536 int tailPos = insPos + 1; 4537 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4538 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4539 reorder[insPos] = dropVal; 4540 } 4541 assert (permuteArgumentChecks(reorder, newType, oldType)); 4542 } 4543 assert (reorder.length == newArity); // a perfect permutation 4544 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4545 form = form.editor().permuteArgumentsForm(1, reorder); 4546 if (newType == result.type() && form == result.internalForm()) 4547 return result; 4548 return result.copyWith(newType, form); 4549 } 4550 4551 /** 4552 * Return an indication of any duplicate or omission in reorder. 4553 * If the reorder contains a duplicate entry, return the index of the second occurrence. 4554 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 4555 * Otherwise, return zero. 4556 * If an element not in [0..newArity-1] is encountered, return reorder.length. 4557 */ 4558 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 4559 final int BIT_LIMIT = 63; // max number of bits in bit mask 4560 if (newArity < BIT_LIMIT) { 4561 long mask = 0; 4562 for (int i = 0; i < reorder.length; i++) { 4563 int arg = reorder[i]; 4564 if (arg >= newArity) { 4565 return reorder.length; 4566 } 4567 long bit = 1L << arg; 4568 if ((mask & bit) != 0) { 4569 return i; // >0 indicates a dup 4570 } 4571 mask |= bit; 4572 } 4573 if (mask == (1L << newArity) - 1) { 4574 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 4575 return 0; 4576 } 4577 // find first zero 4578 long zeroBit = Long.lowestOneBit(~mask); 4579 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 4580 assert(zeroPos <= newArity); 4581 if (zeroPos == newArity) { 4582 return 0; 4583 } 4584 return ~zeroPos; 4585 } else { 4586 // same algorithm, different bit set 4587 BitSet mask = new BitSet(newArity); 4588 for (int i = 0; i < reorder.length; i++) { 4589 int arg = reorder[i]; 4590 if (arg >= newArity) { 4591 return reorder.length; 4592 } 4593 if (mask.get(arg)) { 4594 return i; // >0 indicates a dup 4595 } 4596 mask.set(arg); 4597 } 4598 int zeroPos = mask.nextClearBit(0); 4599 assert(zeroPos <= newArity); 4600 if (zeroPos == newArity) { 4601 return 0; 4602 } 4603 return ~zeroPos; 4604 } 4605 } 4606 4607 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 4608 if (newType.returnType() != oldType.returnType()) 4609 throw newIllegalArgumentException("return types do not match", 4610 oldType, newType); 4611 if (reorder.length == oldType.parameterCount()) { 4612 int limit = newType.parameterCount(); 4613 boolean bad = false; 4614 for (int j = 0; j < reorder.length; j++) { 4615 int i = reorder[j]; 4616 if (i < 0 || i >= limit) { 4617 bad = true; break; 4618 } 4619 Class<?> src = newType.parameterType(i); 4620 Class<?> dst = oldType.parameterType(j); 4621 if (src != dst) 4622 throw newIllegalArgumentException("parameter types do not match after reorder", 4623 oldType, newType); 4624 } 4625 if (!bad) return true; 4626 } 4627 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 4628 } 4629 4630 /** 4631 * Produces a method handle of the requested return type which returns the given 4632 * constant value every time it is invoked. 4633 * <p> 4634 * Before the method handle is returned, the passed-in value is converted to the requested type. 4635 * If the requested type is primitive, widening primitive conversions are attempted, 4636 * else reference conversions are attempted. 4637 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 4638 * @param type the return type of the desired method handle 4639 * @param value the value to return 4640 * @return a method handle of the given return type and no arguments, which always returns the given value 4641 * @throws NullPointerException if the {@code type} argument is null 4642 * @throws ClassCastException if the value cannot be converted to the required return type 4643 * @throws IllegalArgumentException if the given type is {@code void.class} 4644 */ 4645 public static MethodHandle constant(Class<?> type, Object value) { 4646 if (type.isPrimitive()) { 4647 if (type == void.class) 4648 throw newIllegalArgumentException("void type"); 4649 Wrapper w = Wrapper.forPrimitiveType(type); 4650 value = w.convert(value, type); 4651 if (w.zero().equals(value)) 4652 return zero(w, type); 4653 return insertArguments(identity(type), 0, value); 4654 } else { 4655 if (value == null) 4656 return zero(Wrapper.OBJECT, type); 4657 return identity(type).bindTo(value); 4658 } 4659 } 4660 4661 /** 4662 * Produces a method handle which returns its sole argument when invoked. 4663 * @param type the type of the sole parameter and return value of the desired method handle 4664 * @return a unary method handle which accepts and returns the given type 4665 * @throws NullPointerException if the argument is null 4666 * @throws IllegalArgumentException if the given type is {@code void.class} 4667 */ 4668 public static MethodHandle identity(Class<?> type) { 4669 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 4670 int pos = btw.ordinal(); 4671 MethodHandle ident = IDENTITY_MHS[pos]; 4672 if (ident == null) { 4673 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 4674 } 4675 if (ident.type().returnType() == type) 4676 return ident; 4677 // something like identity(Foo.class); do not bother to intern these 4678 assert (btw == Wrapper.OBJECT); 4679 return makeIdentity(type); 4680 } 4681 4682 /** 4683 * Produces a constant method handle of the requested return type which 4684 * returns the default value for that type every time it is invoked. 4685 * The resulting constant method handle will have no side effects. 4686 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 4687 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 4688 * since {@code explicitCastArguments} converts {@code null} to default values. 4689 * @param type the expected return type of the desired method handle 4690 * @return a constant method handle that takes no arguments 4691 * and returns the default value of the given type (or void, if the type is void) 4692 * @throws NullPointerException if the argument is null 4693 * @see MethodHandles#constant 4694 * @see MethodHandles#empty 4695 * @see MethodHandles#explicitCastArguments 4696 * @since 9 4697 */ 4698 public static MethodHandle zero(Class<?> type) { 4699 Objects.requireNonNull(type); 4700 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 4701 } 4702 4703 private static MethodHandle identityOrVoid(Class<?> type) { 4704 return type == void.class ? zero(type) : identity(type); 4705 } 4706 4707 /** 4708 * Produces a method handle of the requested type which ignores any arguments, does nothing, 4709 * and returns a suitable default depending on the return type. 4710 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 4711 * <p>The returned method handle is equivalent to 4712 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 4713 * 4714 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 4715 * {@code guardWithTest(pred, target, empty(target.type())}. 4716 * @param type the type of the desired method handle 4717 * @return a constant method handle of the given type, which returns a default value of the given return type 4718 * @throws NullPointerException if the argument is null 4719 * @see MethodHandles#zero 4720 * @see MethodHandles#constant 4721 * @since 9 4722 */ 4723 public static MethodHandle empty(MethodType type) { 4724 Objects.requireNonNull(type); 4725 return dropArguments(zero(type.returnType()), 0, type.parameterList()); 4726 } 4727 4728 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 4729 private static MethodHandle makeIdentity(Class<?> ptype) { 4730 MethodType mtype = methodType(ptype, ptype); 4731 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 4732 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 4733 } 4734 4735 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 4736 int pos = btw.ordinal(); 4737 MethodHandle zero = ZERO_MHS[pos]; 4738 if (zero == null) { 4739 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 4740 } 4741 if (zero.type().returnType() == rtype) 4742 return zero; 4743 assert(btw == Wrapper.OBJECT); 4744 return makeZero(rtype); 4745 } 4746 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 4747 private static MethodHandle makeZero(Class<?> rtype) { 4748 MethodType mtype = methodType(rtype); 4749 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 4750 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 4751 } 4752 4753 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 4754 // Simulate a CAS, to avoid racy duplication of results. 4755 MethodHandle prev = cache[pos]; 4756 if (prev != null) return prev; 4757 return cache[pos] = value; 4758 } 4759 4760 /** 4761 * Provides a target method handle with one or more <em>bound arguments</em> 4762 * in advance of the method handle's invocation. 4763 * The formal parameters to the target corresponding to the bound 4764 * arguments are called <em>bound parameters</em>. 4765 * Returns a new method handle which saves away the bound arguments. 4766 * When it is invoked, it receives arguments for any non-bound parameters, 4767 * binds the saved arguments to their corresponding parameters, 4768 * and calls the original target. 4769 * <p> 4770 * The type of the new method handle will drop the types for the bound 4771 * parameters from the original target type, since the new method handle 4772 * will no longer require those arguments to be supplied by its callers. 4773 * <p> 4774 * Each given argument object must match the corresponding bound parameter type. 4775 * If a bound parameter type is a primitive, the argument object 4776 * must be a wrapper, and will be unboxed to produce the primitive value. 4777 * <p> 4778 * The {@code pos} argument selects which parameters are to be bound. 4779 * It may range between zero and <i>N-L</i> (inclusively), 4780 * where <i>N</i> is the arity of the target method handle 4781 * and <i>L</i> is the length of the values array. 4782 * <p> 4783 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4784 * variable-arity method handle}, even if the original target method handle was. 4785 * @param target the method handle to invoke after the argument is inserted 4786 * @param pos where to insert the argument (zero for the first) 4787 * @param values the series of arguments to insert 4788 * @return a method handle which inserts an additional argument, 4789 * before calling the original method handle 4790 * @throws NullPointerException if the target or the {@code values} array is null 4791 * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than 4792 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 4793 * is the length of the values array. 4794 * @throws ClassCastException if an argument does not match the corresponding bound parameter 4795 * type. 4796 * @see MethodHandle#bindTo 4797 */ 4798 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 4799 int insCount = values.length; 4800 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 4801 if (insCount == 0) return target; 4802 BoundMethodHandle result = target.rebind(); 4803 for (int i = 0; i < insCount; i++) { 4804 Object value = values[i]; 4805 Class<?> ptype = ptypes[pos+i]; 4806 if (ptype.isPrimitive()) { 4807 result = insertArgumentPrimitive(result, pos, ptype, value); 4808 } else { 4809 value = ptype.cast(value); // throw CCE if needed 4810 result = result.bindArgumentL(pos, value); 4811 } 4812 } 4813 return result; 4814 } 4815 4816 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 4817 Class<?> ptype, Object value) { 4818 Wrapper w = Wrapper.forPrimitiveType(ptype); 4819 // perform unboxing and/or primitive conversion 4820 value = w.convert(value, ptype); 4821 switch (w) { 4822 case INT: return result.bindArgumentI(pos, (int)value); 4823 case LONG: return result.bindArgumentJ(pos, (long)value); 4824 case FLOAT: return result.bindArgumentF(pos, (float)value); 4825 case DOUBLE: return result.bindArgumentD(pos, (double)value); 4826 default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 4827 } 4828 } 4829 4830 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 4831 MethodType oldType = target.type(); 4832 int outargs = oldType.parameterCount(); 4833 int inargs = outargs - insCount; 4834 if (inargs < 0) 4835 throw newIllegalArgumentException("too many values to insert"); 4836 if (pos < 0 || pos > inargs) 4837 throw newIllegalArgumentException("no argument type to append"); 4838 return oldType.ptypes(); 4839 } 4840 4841 /** 4842 * Produces a method handle which will discard some dummy arguments 4843 * before calling some other specified <i>target</i> method handle. 4844 * The type of the new method handle will be the same as the target's type, 4845 * except it will also include the dummy argument types, 4846 * at some given position. 4847 * <p> 4848 * The {@code pos} argument may range between zero and <i>N</i>, 4849 * where <i>N</i> is the arity of the target. 4850 * If {@code pos} is zero, the dummy arguments will precede 4851 * the target's real arguments; if {@code pos} is <i>N</i> 4852 * they will come after. 4853 * <p> 4854 * <b>Example:</b> 4855 * <blockquote><pre>{@code 4856 import static java.lang.invoke.MethodHandles.*; 4857 import static java.lang.invoke.MethodType.*; 4858 ... 4859 MethodHandle cat = lookup().findVirtual(String.class, 4860 "concat", methodType(String.class, String.class)); 4861 assertEquals("xy", (String) cat.invokeExact("x", "y")); 4862 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 4863 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 4864 assertEquals(bigType, d0.type()); 4865 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 4866 * }</pre></blockquote> 4867 * <p> 4868 * This method is also equivalent to the following code: 4869 * <blockquote><pre> 4870 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 4871 * </pre></blockquote> 4872 * @param target the method handle to invoke after the arguments are dropped 4873 * @param pos position of first argument to drop (zero for the leftmost) 4874 * @param valueTypes the type(s) of the argument(s) to drop 4875 * @return a method handle which drops arguments of the given types, 4876 * before calling the original method handle 4877 * @throws NullPointerException if the target is null, 4878 * or if the {@code valueTypes} list or any of its elements is null 4879 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 4880 * or if {@code pos} is negative or greater than the arity of the target, 4881 * or if the new method handle's type would have too many parameters 4882 */ 4883 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 4884 return dropArguments0(target, pos, copyTypes(valueTypes.toArray())); 4885 } 4886 4887 private static List<Class<?>> copyTypes(Object[] array) { 4888 return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class)); 4889 } 4890 4891 private static MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) { 4892 MethodType oldType = target.type(); // get NPE 4893 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 4894 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 4895 if (dropped == 0) return target; 4896 BoundMethodHandle result = target.rebind(); 4897 LambdaForm lform = result.form; 4898 int insertFormArg = 1 + pos; 4899 for (Class<?> ptype : valueTypes) { 4900 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 4901 } 4902 result = result.copyWith(newType, lform); 4903 return result; 4904 } 4905 4906 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { 4907 int dropped = valueTypes.size(); 4908 MethodType.checkSlotCount(dropped); 4909 int outargs = oldType.parameterCount(); 4910 int inargs = outargs + dropped; 4911 if (pos < 0 || pos > outargs) 4912 throw newIllegalArgumentException("no argument type to remove" 4913 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 4914 ); 4915 return dropped; 4916 } 4917 4918 /** 4919 * Produces a method handle which will discard some dummy arguments 4920 * before calling some other specified <i>target</i> method handle. 4921 * The type of the new method handle will be the same as the target's type, 4922 * except it will also include the dummy argument types, 4923 * at some given position. 4924 * <p> 4925 * The {@code pos} argument may range between zero and <i>N</i>, 4926 * where <i>N</i> is the arity of the target. 4927 * If {@code pos} is zero, the dummy arguments will precede 4928 * the target's real arguments; if {@code pos} is <i>N</i> 4929 * they will come after. 4930 * @apiNote 4931 * <blockquote><pre>{@code 4932 import static java.lang.invoke.MethodHandles.*; 4933 import static java.lang.invoke.MethodType.*; 4934 ... 4935 MethodHandle cat = lookup().findVirtual(String.class, 4936 "concat", methodType(String.class, String.class)); 4937 assertEquals("xy", (String) cat.invokeExact("x", "y")); 4938 MethodHandle d0 = dropArguments(cat, 0, String.class); 4939 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 4940 MethodHandle d1 = dropArguments(cat, 1, String.class); 4941 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 4942 MethodHandle d2 = dropArguments(cat, 2, String.class); 4943 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 4944 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 4945 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 4946 * }</pre></blockquote> 4947 * <p> 4948 * This method is also equivalent to the following code: 4949 * <blockquote><pre> 4950 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 4951 * </pre></blockquote> 4952 * @param target the method handle to invoke after the arguments are dropped 4953 * @param pos position of first argument to drop (zero for the leftmost) 4954 * @param valueTypes the type(s) of the argument(s) to drop 4955 * @return a method handle which drops arguments of the given types, 4956 * before calling the original method handle 4957 * @throws NullPointerException if the target is null, 4958 * or if the {@code valueTypes} array or any of its elements is null 4959 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 4960 * or if {@code pos} is negative or greater than the arity of the target, 4961 * or if the new method handle's type would have 4962 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4963 */ 4964 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 4965 return dropArguments0(target, pos, copyTypes(valueTypes)); 4966 } 4967 4968 // private version which allows caller some freedom with error handling 4969 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, 4970 boolean nullOnFailure) { 4971 newTypes = copyTypes(newTypes.toArray()); 4972 List<Class<?>> oldTypes = target.type().parameterList(); 4973 int match = oldTypes.size(); 4974 if (skip != 0) { 4975 if (skip < 0 || skip > match) { 4976 throw newIllegalArgumentException("illegal skip", skip, target); 4977 } 4978 oldTypes = oldTypes.subList(skip, match); 4979 match -= skip; 4980 } 4981 List<Class<?>> addTypes = newTypes; 4982 int add = addTypes.size(); 4983 if (pos != 0) { 4984 if (pos < 0 || pos > add) { 4985 throw newIllegalArgumentException("illegal pos", pos, newTypes); 4986 } 4987 addTypes = addTypes.subList(pos, add); 4988 add -= pos; 4989 assert(addTypes.size() == add); 4990 } 4991 // Do not add types which already match the existing arguments. 4992 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { 4993 if (nullOnFailure) { 4994 return null; 4995 } 4996 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); 4997 } 4998 addTypes = addTypes.subList(match, add); 4999 add -= match; 5000 assert(addTypes.size() == add); 5001 // newTypes: ( P*[pos], M*[match], A*[add] ) 5002 // target: ( S*[skip], M*[match] ) 5003 MethodHandle adapter = target; 5004 if (add > 0) { 5005 adapter = dropArguments0(adapter, skip+ match, addTypes); 5006 } 5007 // adapter: (S*[skip], M*[match], A*[add] ) 5008 if (pos > 0) { 5009 adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos)); 5010 } 5011 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5012 return adapter; 5013 } 5014 5015 /** 5016 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5017 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5018 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5019 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5020 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5021 * {@link #dropArguments(MethodHandle, int, Class[])}. 5022 * <p> 5023 * The resulting handle will have the same return type as the target handle. 5024 * <p> 5025 * In more formal terms, assume these two type lists:<ul> 5026 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5027 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5028 * {@code newTypes}. 5029 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5030 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5031 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5032 * sub-list. 5033 * </ul> 5034 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5035 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5036 * {@link #dropArguments(MethodHandle, int, Class[])}. 5037 * 5038 * @apiNote 5039 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5040 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5041 * <blockquote><pre>{@code 5042 import static java.lang.invoke.MethodHandles.*; 5043 import static java.lang.invoke.MethodType.*; 5044 ... 5045 ... 5046 MethodHandle h0 = constant(boolean.class, true); 5047 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5048 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5049 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5050 if (h1.type().parameterCount() < h2.type().parameterCount()) 5051 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5052 else 5053 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5054 MethodHandle h3 = guardWithTest(h0, h1, h2); 5055 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5056 * }</pre></blockquote> 5057 * @param target the method handle to adapt 5058 * @param skip number of targets parameters to disregard (they will be unchanged) 5059 * @param newTypes the list of types to match {@code target}'s parameter type list to 5060 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5061 * @return a possibly adapted method handle 5062 * @throws NullPointerException if either argument is null 5063 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5064 * or if {@code skip} is negative or greater than the arity of the target, 5065 * or if {@code pos} is negative or greater than the newTypes list size, 5066 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5067 * {@code pos}. 5068 * @since 9 5069 */ 5070 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5071 Objects.requireNonNull(target); 5072 Objects.requireNonNull(newTypes); 5073 return dropArgumentsToMatch(target, skip, newTypes, pos, false); 5074 } 5075 5076 /** 5077 * Adapts a target method handle by pre-processing 5078 * one or more of its arguments, each with its own unary filter function, 5079 * and then calling the target with each pre-processed argument 5080 * replaced by the result of its corresponding filter function. 5081 * <p> 5082 * The pre-processing is performed by one or more method handles, 5083 * specified in the elements of the {@code filters} array. 5084 * The first element of the filter array corresponds to the {@code pos} 5085 * argument of the target, and so on in sequence. 5086 * The filter functions are invoked in left to right order. 5087 * <p> 5088 * Null arguments in the array are treated as identity functions, 5089 * and the corresponding arguments left unchanged. 5090 * (If there are no non-null elements in the array, the original target is returned.) 5091 * Each filter is applied to the corresponding argument of the adapter. 5092 * <p> 5093 * If a filter {@code F} applies to the {@code N}th argument of 5094 * the target, then {@code F} must be a method handle which 5095 * takes exactly one argument. The type of {@code F}'s sole argument 5096 * replaces the corresponding argument type of the target 5097 * in the resulting adapted method handle. 5098 * The return type of {@code F} must be identical to the corresponding 5099 * parameter type of the target. 5100 * <p> 5101 * It is an error if there are elements of {@code filters} 5102 * (null or not) 5103 * which do not correspond to argument positions in the target. 5104 * <p><b>Example:</b> 5105 * <blockquote><pre>{@code 5106 import static java.lang.invoke.MethodHandles.*; 5107 import static java.lang.invoke.MethodType.*; 5108 ... 5109 MethodHandle cat = lookup().findVirtual(String.class, 5110 "concat", methodType(String.class, String.class)); 5111 MethodHandle upcase = lookup().findVirtual(String.class, 5112 "toUpperCase", methodType(String.class)); 5113 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5114 MethodHandle f0 = filterArguments(cat, 0, upcase); 5115 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5116 MethodHandle f1 = filterArguments(cat, 1, upcase); 5117 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5118 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5119 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5120 * }</pre></blockquote> 5121 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5122 * denotes the return type of both the {@code target} and resulting adapter. 5123 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5124 * of the parameters and arguments that precede and follow the filter position 5125 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5126 * values of the filtered parameters and arguments; they also represent the 5127 * return types of the {@code filter[i]} handles. The latter accept arguments 5128 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5129 * the resulting adapter. 5130 * <blockquote><pre>{@code 5131 * T target(P... p, A[i]... a[i], B... b); 5132 * A[i] filter[i](V[i]); 5133 * T adapter(P... p, V[i]... v[i], B... b) { 5134 * return target(p..., filter[i](v[i])..., b...); 5135 * } 5136 * }</pre></blockquote> 5137 * <p> 5138 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5139 * variable-arity method handle}, even if the original target method handle was. 5140 * 5141 * @param target the method handle to invoke after arguments are filtered 5142 * @param pos the position of the first argument to filter 5143 * @param filters method handles to call initially on filtered arguments 5144 * @return method handle which incorporates the specified argument filtering logic 5145 * @throws NullPointerException if the target is null 5146 * or if the {@code filters} array is null 5147 * @throws IllegalArgumentException if a non-null element of {@code filters} 5148 * does not match a corresponding argument type of target as described above, 5149 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5150 * or if the resulting method handle's type would have 5151 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5152 */ 5153 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5154 // In method types arguments start at index 0, while the LF 5155 // editor have the MH receiver at position 0 - adjust appropriately. 5156 final int MH_RECEIVER_OFFSET = 1; 5157 filterArgumentsCheckArity(target, pos, filters); 5158 MethodHandle adapter = target; 5159 5160 // keep track of currently matched filters, as to optimize repeated filters 5161 int index = 0; 5162 int[] positions = new int[filters.length]; 5163 MethodHandle filter = null; 5164 5165 // process filters in reverse order so that the invocation of 5166 // the resulting adapter will invoke the filters in left-to-right order 5167 for (int i = filters.length - 1; i >= 0; --i) { 5168 MethodHandle newFilter = filters[i]; 5169 if (newFilter == null) continue; // ignore null elements of filters 5170 5171 // flush changes on update 5172 if (filter != newFilter) { 5173 if (filter != null) { 5174 if (index > 1) { 5175 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5176 } else { 5177 adapter = filterArgument(adapter, positions[0] - 1, filter); 5178 } 5179 } 5180 filter = newFilter; 5181 index = 0; 5182 } 5183 5184 filterArgumentChecks(target, pos + i, newFilter); 5185 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5186 } 5187 if (index > 1) { 5188 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5189 } else if (index == 1) { 5190 adapter = filterArgument(adapter, positions[0] - 1, filter); 5191 } 5192 return adapter; 5193 } 5194 5195 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5196 MethodType targetType = adapter.type(); 5197 MethodType filterType = filter.type(); 5198 BoundMethodHandle result = adapter.rebind(); 5199 Class<?> newParamType = filterType.parameterType(0); 5200 5201 Class<?>[] ptypes = targetType.ptypes().clone(); 5202 for (int pos : positions) { 5203 ptypes[pos - 1] = newParamType; 5204 } 5205 MethodType newType = MethodType.makeImpl(targetType.rtype(), ptypes, true); 5206 5207 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5208 return result.copyWithExtendL(newType, lform, filter); 5209 } 5210 5211 /*non-public*/ 5212 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5213 filterArgumentChecks(target, pos, filter); 5214 MethodType targetType = target.type(); 5215 MethodType filterType = filter.type(); 5216 BoundMethodHandle result = target.rebind(); 5217 Class<?> newParamType = filterType.parameterType(0); 5218 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5219 MethodType newType = targetType.changeParameterType(pos, newParamType); 5220 result = result.copyWithExtendL(newType, lform, filter); 5221 return result; 5222 } 5223 5224 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5225 MethodType targetType = target.type(); 5226 int maxPos = targetType.parameterCount(); 5227 if (pos + filters.length > maxPos) 5228 throw newIllegalArgumentException("too many filters"); 5229 } 5230 5231 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5232 MethodType targetType = target.type(); 5233 MethodType filterType = filter.type(); 5234 if (filterType.parameterCount() != 1 5235 || filterType.returnType() != targetType.parameterType(pos)) 5236 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5237 } 5238 5239 /** 5240 * Adapts a target method handle by pre-processing 5241 * a sub-sequence of its arguments with a filter (another method handle). 5242 * The pre-processed arguments are replaced by the result (if any) of the 5243 * filter function. 5244 * The target is then called on the modified (usually shortened) argument list. 5245 * <p> 5246 * If the filter returns a value, the target must accept that value as 5247 * its argument in position {@code pos}, preceded and/or followed by 5248 * any arguments not passed to the filter. 5249 * If the filter returns void, the target must accept all arguments 5250 * not passed to the filter. 5251 * No arguments are reordered, and a result returned from the filter 5252 * replaces (in order) the whole subsequence of arguments originally 5253 * passed to the adapter. 5254 * <p> 5255 * The argument types (if any) of the filter 5256 * replace zero or one argument types of the target, at position {@code pos}, 5257 * in the resulting adapted method handle. 5258 * The return type of the filter (if any) must be identical to the 5259 * argument type of the target at position {@code pos}, and that target argument 5260 * is supplied by the return value of the filter. 5261 * <p> 5262 * In all cases, {@code pos} must be greater than or equal to zero, and 5263 * {@code pos} must also be less than or equal to the target's arity. 5264 * <p><b>Example:</b> 5265 * <blockquote><pre>{@code 5266 import static java.lang.invoke.MethodHandles.*; 5267 import static java.lang.invoke.MethodType.*; 5268 ... 5269 MethodHandle deepToString = publicLookup() 5270 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5271 5272 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5273 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5274 5275 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5276 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5277 5278 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5279 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5280 assertEquals("[top, [up, down], strange]", 5281 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5282 5283 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5284 assertEquals("[top, [up, down], [strange]]", 5285 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5286 5287 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5288 assertEquals("[top, [[up, down, strange], charm], bottom]", 5289 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5290 * }</pre></blockquote> 5291 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5292 * represents the return type of the {@code target} and resulting adapter. 5293 * {@code V}/{@code v} stand for the return type and value of the 5294 * {@code filter}, which are also found in the signature and arguments of 5295 * the {@code target}, respectively, unless {@code V} is {@code void}. 5296 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5297 * and values preceding and following the collection position, {@code pos}, 5298 * in the {@code target}'s signature. They also turn up in the resulting 5299 * adapter's signature and arguments, where they surround 5300 * {@code B}/{@code b}, which represent the parameter types and arguments 5301 * to the {@code filter} (if any). 5302 * <blockquote><pre>{@code 5303 * T target(A...,V,C...); 5304 * V filter(B...); 5305 * T adapter(A... a,B... b,C... c) { 5306 * V v = filter(b...); 5307 * return target(a...,v,c...); 5308 * } 5309 * // and if the filter has no arguments: 5310 * T target2(A...,V,C...); 5311 * V filter2(); 5312 * T adapter2(A... a,C... c) { 5313 * V v = filter2(); 5314 * return target2(a...,v,c...); 5315 * } 5316 * // and if the filter has a void return: 5317 * T target3(A...,C...); 5318 * void filter3(B...); 5319 * T adapter3(A... a,B... b,C... c) { 5320 * filter3(b...); 5321 * return target3(a...,c...); 5322 * } 5323 * }</pre></blockquote> 5324 * <p> 5325 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5326 * one which first "folds" the affected arguments, and then drops them, in separate 5327 * steps as follows: 5328 * <blockquote><pre>{@code 5329 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5330 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5331 * }</pre></blockquote> 5332 * If the target method handle consumes no arguments besides than the result 5333 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5334 * is equivalent to {@code filterReturnValue(coll, mh)}. 5335 * If the filter method handle {@code coll} consumes one argument and produces 5336 * a non-void result, then {@code collectArguments(mh, N, coll)} 5337 * is equivalent to {@code filterArguments(mh, N, coll)}. 5338 * Other equivalences are possible but would require argument permutation. 5339 * <p> 5340 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5341 * variable-arity method handle}, even if the original target method handle was. 5342 * 5343 * @param target the method handle to invoke after filtering the subsequence of arguments 5344 * @param pos the position of the first adapter argument to pass to the filter, 5345 * and/or the target argument which receives the result of the filter 5346 * @param filter method handle to call on the subsequence of arguments 5347 * @return method handle which incorporates the specified argument subsequence filtering logic 5348 * @throws NullPointerException if either argument is null 5349 * @throws IllegalArgumentException if the return type of {@code filter} 5350 * is non-void and is not the same as the {@code pos} argument of the target, 5351 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5352 * or if the resulting method handle's type would have 5353 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5354 * @see MethodHandles#foldArguments 5355 * @see MethodHandles#filterArguments 5356 * @see MethodHandles#filterReturnValue 5357 */ 5358 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5359 MethodType newType = collectArgumentsChecks(target, pos, filter); 5360 MethodType collectorType = filter.type(); 5361 BoundMethodHandle result = target.rebind(); 5362 LambdaForm lform; 5363 if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { 5364 lform = result.editor().collectArgumentArrayForm(1 + pos, filter); 5365 if (lform != null) { 5366 return result.copyWith(newType, lform); 5367 } 5368 } 5369 lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5370 return result.copyWithExtendL(newType, lform, filter); 5371 } 5372 5373 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5374 MethodType targetType = target.type(); 5375 MethodType filterType = filter.type(); 5376 Class<?> rtype = filterType.returnType(); 5377 List<Class<?>> filterArgs = filterType.parameterList(); 5378 if (rtype == void.class) { 5379 return targetType.insertParameterTypes(pos, filterArgs); 5380 } 5381 if (rtype != targetType.parameterType(pos)) { 5382 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5383 } 5384 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); 5385 } 5386 5387 /** 5388 * Adapts a target method handle by post-processing 5389 * its return value (if any) with a filter (another method handle). 5390 * The result of the filter is returned from the adapter. 5391 * <p> 5392 * If the target returns a value, the filter must accept that value as 5393 * its only argument. 5394 * If the target returns void, the filter must accept no arguments. 5395 * <p> 5396 * The return type of the filter 5397 * replaces the return type of the target 5398 * in the resulting adapted method handle. 5399 * The argument type of the filter (if any) must be identical to the 5400 * return type of the target. 5401 * <p><b>Example:</b> 5402 * <blockquote><pre>{@code 5403 import static java.lang.invoke.MethodHandles.*; 5404 import static java.lang.invoke.MethodType.*; 5405 ... 5406 MethodHandle cat = lookup().findVirtual(String.class, 5407 "concat", methodType(String.class, String.class)); 5408 MethodHandle length = lookup().findVirtual(String.class, 5409 "length", methodType(int.class)); 5410 System.out.println((String) cat.invokeExact("x", "y")); // xy 5411 MethodHandle f0 = filterReturnValue(cat, length); 5412 System.out.println((int) f0.invokeExact("x", "y")); // 2 5413 * }</pre></blockquote> 5414 * <p>Here is pseudocode for the resulting adapter. In the code, 5415 * {@code T}/{@code t} represent the result type and value of the 5416 * {@code target}; {@code V}, the result type of the {@code filter}; and 5417 * {@code A}/{@code a}, the types and values of the parameters and arguments 5418 * of the {@code target} as well as the resulting adapter. 5419 * <blockquote><pre>{@code 5420 * T target(A...); 5421 * V filter(T); 5422 * V adapter(A... a) { 5423 * T t = target(a...); 5424 * return filter(t); 5425 * } 5426 * // and if the target has a void return: 5427 * void target2(A...); 5428 * V filter2(); 5429 * V adapter2(A... a) { 5430 * target2(a...); 5431 * return filter2(); 5432 * } 5433 * // and if the filter has a void return: 5434 * T target3(A...); 5435 * void filter3(V); 5436 * void adapter3(A... a) { 5437 * T t = target3(a...); 5438 * filter3(t); 5439 * } 5440 * }</pre></blockquote> 5441 * <p> 5442 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5443 * variable-arity method handle}, even if the original target method handle was. 5444 * @param target the method handle to invoke before filtering the return value 5445 * @param filter method handle to call on the return value 5446 * @return method handle which incorporates the specified return value filtering logic 5447 * @throws NullPointerException if either argument is null 5448 * @throws IllegalArgumentException if the argument list of {@code filter} 5449 * does not match the return type of target as described above 5450 */ 5451 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5452 MethodType targetType = target.type(); 5453 MethodType filterType = filter.type(); 5454 filterReturnValueChecks(targetType, filterType); 5455 BoundMethodHandle result = target.rebind(); 5456 BasicType rtype = BasicType.basicType(filterType.returnType()); 5457 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5458 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5459 result = result.copyWithExtendL(newType, lform, filter); 5460 return result; 5461 } 5462 5463 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5464 Class<?> rtype = targetType.returnType(); 5465 int filterValues = filterType.parameterCount(); 5466 if (filterValues == 0 5467 ? (rtype != void.class) 5468 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5469 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5470 } 5471 5472 /** 5473 * Adapts a target method handle by pre-processing 5474 * some of its arguments, and then calling the target with 5475 * the result of the pre-processing, inserted into the original 5476 * sequence of arguments. 5477 * <p> 5478 * The pre-processing is performed by {@code combiner}, a second method handle. 5479 * Of the arguments passed to the adapter, the first {@code N} arguments 5480 * are copied to the combiner, which is then called. 5481 * (Here, {@code N} is defined as the parameter count of the combiner.) 5482 * After this, control passes to the target, with any result 5483 * from the combiner inserted before the original {@code N} incoming 5484 * arguments. 5485 * <p> 5486 * If the combiner returns a value, the first parameter type of the target 5487 * must be identical with the return type of the combiner, and the next 5488 * {@code N} parameter types of the target must exactly match the parameters 5489 * of the combiner. 5490 * <p> 5491 * If the combiner has a void return, no result will be inserted, 5492 * and the first {@code N} parameter types of the target 5493 * must exactly match the parameters of the combiner. 5494 * <p> 5495 * The resulting adapter is the same type as the target, except that the 5496 * first parameter type is dropped, 5497 * if it corresponds to the result of the combiner. 5498 * <p> 5499 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 5500 * that either the combiner or the target does not wish to receive. 5501 * If some of the incoming arguments are destined only for the combiner, 5502 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 5503 * arguments will not need to be live on the stack on entry to the 5504 * target.) 5505 * <p><b>Example:</b> 5506 * <blockquote><pre>{@code 5507 import static java.lang.invoke.MethodHandles.*; 5508 import static java.lang.invoke.MethodType.*; 5509 ... 5510 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5511 "println", methodType(void.class, String.class)) 5512 .bindTo(System.out); 5513 MethodHandle cat = lookup().findVirtual(String.class, 5514 "concat", methodType(String.class, String.class)); 5515 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5516 MethodHandle catTrace = foldArguments(cat, trace); 5517 // also prints "boo": 5518 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5519 * }</pre></blockquote> 5520 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5521 * represents the result type of the {@code target} and resulting adapter. 5522 * {@code V}/{@code v} represent the type and value of the parameter and argument 5523 * of {@code target} that precedes the folding position; {@code V} also is 5524 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5525 * types and values of the {@code N} parameters and arguments at the folding 5526 * position. {@code B}/{@code b} represent the types and values of the 5527 * {@code target} parameters and arguments that follow the folded parameters 5528 * and arguments. 5529 * <blockquote><pre>{@code 5530 * // there are N arguments in A... 5531 * T target(V, A[N]..., B...); 5532 * V combiner(A...); 5533 * T adapter(A... a, B... b) { 5534 * V v = combiner(a...); 5535 * return target(v, a..., b...); 5536 * } 5537 * // and if the combiner has a void return: 5538 * T target2(A[N]..., B...); 5539 * void combiner2(A...); 5540 * T adapter2(A... a, B... b) { 5541 * combiner2(a...); 5542 * return target2(a..., b...); 5543 * } 5544 * }</pre></blockquote> 5545 * <p> 5546 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5547 * variable-arity method handle}, even if the original target method handle was. 5548 * @param target the method handle to invoke after arguments are combined 5549 * @param combiner method handle to call initially on the incoming arguments 5550 * @return method handle which incorporates the specified argument folding logic 5551 * @throws NullPointerException if either argument is null 5552 * @throws IllegalArgumentException if {@code combiner}'s return type 5553 * is non-void and not the same as the first argument type of 5554 * the target, or if the initial {@code N} argument types 5555 * of the target 5556 * (skipping one matching the {@code combiner}'s return type) 5557 * are not identical with the argument types of {@code combiner} 5558 */ 5559 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 5560 return foldArguments(target, 0, combiner); 5561 } 5562 5563 /** 5564 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 5565 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 5566 * before the folded arguments. 5567 * <p> 5568 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 5569 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 5570 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 5571 * 0. 5572 * 5573 * @apiNote Example: 5574 * <blockquote><pre>{@code 5575 import static java.lang.invoke.MethodHandles.*; 5576 import static java.lang.invoke.MethodType.*; 5577 ... 5578 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5579 "println", methodType(void.class, String.class)) 5580 .bindTo(System.out); 5581 MethodHandle cat = lookup().findVirtual(String.class, 5582 "concat", methodType(String.class, String.class)); 5583 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5584 MethodHandle catTrace = foldArguments(cat, 1, trace); 5585 // also prints "jum": 5586 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5587 * }</pre></blockquote> 5588 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5589 * represents the result type of the {@code target} and resulting adapter. 5590 * {@code V}/{@code v} represent the type and value of the parameter and argument 5591 * of {@code target} that precedes the folding position; {@code V} also is 5592 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5593 * types and values of the {@code N} parameters and arguments at the folding 5594 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 5595 * and values of the {@code target} parameters and arguments that precede and 5596 * follow the folded parameters and arguments starting at {@code pos}, 5597 * respectively. 5598 * <blockquote><pre>{@code 5599 * // there are N arguments in A... 5600 * T target(Z..., V, A[N]..., B...); 5601 * V combiner(A...); 5602 * T adapter(Z... z, A... a, B... b) { 5603 * V v = combiner(a...); 5604 * return target(z..., v, a..., b...); 5605 * } 5606 * // and if the combiner has a void return: 5607 * T target2(Z..., A[N]..., B...); 5608 * void combiner2(A...); 5609 * T adapter2(Z... z, A... a, B... b) { 5610 * combiner2(a...); 5611 * return target2(z..., a..., b...); 5612 * } 5613 * }</pre></blockquote> 5614 * <p> 5615 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5616 * variable-arity method handle}, even if the original target method handle was. 5617 * 5618 * @param target the method handle to invoke after arguments are combined 5619 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 5620 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5621 * @param combiner method handle to call initially on the incoming arguments 5622 * @return method handle which incorporates the specified argument folding logic 5623 * @throws NullPointerException if either argument is null 5624 * @throws IllegalArgumentException if either of the following two conditions holds: 5625 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5626 * {@code pos} of the target signature; 5627 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 5628 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 5629 * 5630 * @see #foldArguments(MethodHandle, MethodHandle) 5631 * @since 9 5632 */ 5633 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 5634 MethodType targetType = target.type(); 5635 MethodType combinerType = combiner.type(); 5636 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 5637 BoundMethodHandle result = target.rebind(); 5638 boolean dropResult = rtype == void.class; 5639 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 5640 MethodType newType = targetType; 5641 if (!dropResult) { 5642 newType = newType.dropParameterTypes(pos, pos + 1); 5643 } 5644 result = result.copyWithExtendL(newType, lform, combiner); 5645 return result; 5646 } 5647 5648 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 5649 int foldArgs = combinerType.parameterCount(); 5650 Class<?> rtype = combinerType.returnType(); 5651 int foldVals = rtype == void.class ? 0 : 1; 5652 int afterInsertPos = foldPos + foldVals; 5653 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 5654 if (ok) { 5655 for (int i = 0; i < foldArgs; i++) { 5656 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 5657 ok = false; 5658 break; 5659 } 5660 } 5661 } 5662 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 5663 ok = false; 5664 if (!ok) 5665 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5666 return rtype; 5667 } 5668 5669 /** 5670 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 5671 * of the pre-processing replacing the argument at the given position. 5672 * 5673 * @param target the method handle to invoke after arguments are combined 5674 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5675 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5676 * @param combiner method handle to call initially on the incoming arguments 5677 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5678 * @return method handle which incorporates the specified argument folding logic 5679 * @throws NullPointerException if either argument is null 5680 * @throws IllegalArgumentException if either of the following two conditions holds: 5681 * (1) {@code combiner}'s return type is not the same as the argument type at position 5682 * {@code pos} of the target signature; 5683 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 5684 * not identical with the argument types of {@code combiner}. 5685 */ 5686 /*non-public*/ 5687 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5688 return argumentsWithCombiner(true, target, position, combiner, argPositions); 5689 } 5690 5691 /** 5692 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 5693 * the pre-processing inserted into the original sequence of arguments at the given position. 5694 * 5695 * @param target the method handle to invoke after arguments are combined 5696 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5697 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5698 * @param combiner method handle to call initially on the incoming arguments 5699 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5700 * @return method handle which incorporates the specified argument folding logic 5701 * @throws NullPointerException if either argument is null 5702 * @throws IllegalArgumentException if either of the following two conditions holds: 5703 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5704 * {@code pos} of the target signature; 5705 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 5706 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 5707 * with the argument types of {@code combiner}. 5708 */ 5709 /*non-public*/ 5710 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5711 return argumentsWithCombiner(false, target, position, combiner, argPositions); 5712 } 5713 5714 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5715 MethodType targetType = target.type(); 5716 MethodType combinerType = combiner.type(); 5717 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 5718 BoundMethodHandle result = target.rebind(); 5719 5720 MethodType newType = targetType; 5721 LambdaForm lform; 5722 if (filter) { 5723 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 5724 } else { 5725 boolean dropResult = rtype == void.class; 5726 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 5727 if (!dropResult) { 5728 newType = newType.dropParameterTypes(position, position + 1); 5729 } 5730 } 5731 result = result.copyWithExtendL(newType, lform, combiner); 5732 return result; 5733 } 5734 5735 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 5736 int combinerArgs = combinerType.parameterCount(); 5737 if (argPos.length != combinerArgs) { 5738 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 5739 } 5740 Class<?> rtype = combinerType.returnType(); 5741 5742 for (int i = 0; i < combinerArgs; i++) { 5743 int arg = argPos[i]; 5744 if (arg < 0 || arg > targetType.parameterCount()) { 5745 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 5746 } 5747 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 5748 throw newIllegalArgumentException("target argument type at position " + arg 5749 + " must match combiner argument type at index " + i + ": " + targetType 5750 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 5751 } 5752 } 5753 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 5754 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5755 } 5756 return rtype; 5757 } 5758 5759 /** 5760 * Makes a method handle which adapts a target method handle, 5761 * by guarding it with a test, a boolean-valued method handle. 5762 * If the guard fails, a fallback handle is called instead. 5763 * All three method handles must have the same corresponding 5764 * argument and return types, except that the return type 5765 * of the test must be boolean, and the test is allowed 5766 * to have fewer arguments than the other two method handles. 5767 * <p> 5768 * Here is pseudocode for the resulting adapter. In the code, {@code T} 5769 * represents the uniform result type of the three involved handles; 5770 * {@code A}/{@code a}, the types and values of the {@code target} 5771 * parameters and arguments that are consumed by the {@code test}; and 5772 * {@code B}/{@code b}, those types and values of the {@code target} 5773 * parameters and arguments that are not consumed by the {@code test}. 5774 * <blockquote><pre>{@code 5775 * boolean test(A...); 5776 * T target(A...,B...); 5777 * T fallback(A...,B...); 5778 * T adapter(A... a,B... b) { 5779 * if (test(a...)) 5780 * return target(a..., b...); 5781 * else 5782 * return fallback(a..., b...); 5783 * } 5784 * }</pre></blockquote> 5785 * Note that the test arguments ({@code a...} in the pseudocode) cannot 5786 * be modified by execution of the test, and so are passed unchanged 5787 * from the caller to the target or fallback as appropriate. 5788 * @param test method handle used for test, must return boolean 5789 * @param target method handle to call if test passes 5790 * @param fallback method handle to call if test fails 5791 * @return method handle which incorporates the specified if/then/else logic 5792 * @throws NullPointerException if any argument is null 5793 * @throws IllegalArgumentException if {@code test} does not return boolean, 5794 * or if all three method types do not match (with the return 5795 * type of {@code test} changed to match that of the target). 5796 */ 5797 public static MethodHandle guardWithTest(MethodHandle test, 5798 MethodHandle target, 5799 MethodHandle fallback) { 5800 MethodType gtype = test.type(); 5801 MethodType ttype = target.type(); 5802 MethodType ftype = fallback.type(); 5803 if (!ttype.equals(ftype)) 5804 throw misMatchedTypes("target and fallback types", ttype, ftype); 5805 if (gtype.returnType() != boolean.class) 5806 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 5807 List<Class<?>> targs = ttype.parameterList(); 5808 test = dropArgumentsToMatch(test, 0, targs, 0, true); 5809 if (test == null) { 5810 throw misMatchedTypes("target and test types", ttype, gtype); 5811 } 5812 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 5813 } 5814 5815 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 5816 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 5817 } 5818 5819 /** 5820 * Makes a method handle which adapts a target method handle, 5821 * by running it inside an exception handler. 5822 * If the target returns normally, the adapter returns that value. 5823 * If an exception matching the specified type is thrown, the fallback 5824 * handle is called instead on the exception, plus the original arguments. 5825 * <p> 5826 * The target and handler must have the same corresponding 5827 * argument and return types, except that handler may omit trailing arguments 5828 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 5829 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 5830 * <p> 5831 * Here is pseudocode for the resulting adapter. In the code, {@code T} 5832 * represents the return type of the {@code target} and {@code handler}, 5833 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 5834 * the types and values of arguments to the resulting handle consumed by 5835 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 5836 * resulting handle discarded by {@code handler}. 5837 * <blockquote><pre>{@code 5838 * T target(A..., B...); 5839 * T handler(ExType, A...); 5840 * T adapter(A... a, B... b) { 5841 * try { 5842 * return target(a..., b...); 5843 * } catch (ExType ex) { 5844 * return handler(ex, a...); 5845 * } 5846 * } 5847 * }</pre></blockquote> 5848 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 5849 * be modified by execution of the target, and so are passed unchanged 5850 * from the caller to the handler, if the handler is invoked. 5851 * <p> 5852 * The target and handler must return the same type, even if the handler 5853 * always throws. (This might happen, for instance, because the handler 5854 * is simulating a {@code finally} clause). 5855 * To create such a throwing handler, compose the handler creation logic 5856 * with {@link #throwException throwException}, 5857 * in order to create a method handle of the correct return type. 5858 * @param target method handle to call 5859 * @param exType the type of exception which the handler will catch 5860 * @param handler method handle to call if a matching exception is thrown 5861 * @return method handle which incorporates the specified try/catch logic 5862 * @throws NullPointerException if any argument is null 5863 * @throws IllegalArgumentException if {@code handler} does not accept 5864 * the given exception type, or if the method handle types do 5865 * not match in their return types and their 5866 * corresponding parameters 5867 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 5868 */ 5869 public static MethodHandle catchException(MethodHandle target, 5870 Class<? extends Throwable> exType, 5871 MethodHandle handler) { 5872 MethodType ttype = target.type(); 5873 MethodType htype = handler.type(); 5874 if (!Throwable.class.isAssignableFrom(exType)) 5875 throw new ClassCastException(exType.getName()); 5876 if (htype.parameterCount() < 1 || 5877 !htype.parameterType(0).isAssignableFrom(exType)) 5878 throw newIllegalArgumentException("handler does not accept exception type "+exType); 5879 if (htype.returnType() != ttype.returnType()) 5880 throw misMatchedTypes("target and handler return types", ttype, htype); 5881 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); 5882 if (handler == null) { 5883 throw misMatchedTypes("target and handler types", ttype, htype); 5884 } 5885 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 5886 } 5887 5888 /** 5889 * Produces a method handle which will throw exceptions of the given {@code exType}. 5890 * The method handle will accept a single argument of {@code exType}, 5891 * and immediately throw it as an exception. 5892 * The method type will nominally specify a return of {@code returnType}. 5893 * The return type may be anything convenient: It doesn't matter to the 5894 * method handle's behavior, since it will never return normally. 5895 * @param returnType the return type of the desired method handle 5896 * @param exType the parameter type of the desired method handle 5897 * @return method handle which can throw the given exceptions 5898 * @throws NullPointerException if either argument is null 5899 */ 5900 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 5901 if (!Throwable.class.isAssignableFrom(exType)) 5902 throw new ClassCastException(exType.getName()); 5903 return MethodHandleImpl.throwException(methodType(returnType, exType)); 5904 } 5905 5906 /** 5907 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 5908 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 5909 * delivers the loop's result, which is the return value of the resulting handle. 5910 * <p> 5911 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 5912 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 5913 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 5914 * terms of method handles, each clause will specify up to four independent actions:<ul> 5915 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 5916 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 5917 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 5918 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 5919 * </ul> 5920 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 5921 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 5922 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 5923 * <p> 5924 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 5925 * this case. See below for a detailed description. 5926 * <p> 5927 * <em>Parameters optional everywhere:</em> 5928 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 5929 * As an exception, the init functions cannot take any {@code v} parameters, 5930 * because those values are not yet computed when the init functions are executed. 5931 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 5932 * In fact, any clause function may take no arguments at all. 5933 * <p> 5934 * <em>Loop parameters:</em> 5935 * A clause function may take all the iteration variable values it is entitled to, in which case 5936 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 5937 * with their types and values notated as {@code (A...)} and {@code (a...)}. 5938 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 5939 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 5940 * init function is automatically a loop parameter {@code a}.) 5941 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 5942 * These loop parameters act as loop-invariant values visible across the whole loop. 5943 * <p> 5944 * <em>Parameters visible everywhere:</em> 5945 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 5946 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 5947 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 5948 * Most clause functions will not need all of this information, but they will be formally connected to it 5949 * as if by {@link #dropArguments}. 5950 * <a id="astar"></a> 5951 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 5952 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 5953 * In that notation, the general form of an init function parameter list 5954 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 5955 * <p> 5956 * <em>Checking clause structure:</em> 5957 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 5958 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 5959 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 5960 * met by the inputs to the loop combinator. 5961 * <p> 5962 * <em>Effectively identical sequences:</em> 5963 * <a id="effid"></a> 5964 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 5965 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 5966 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 5967 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 5968 * that longest list. 5969 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 5970 * and the same is true if more sequences of the form {@code (V... A*)} are added. 5971 * <p> 5972 * <em>Step 0: Determine clause structure.</em><ol type="a"> 5973 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 5974 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 5975 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 5976 * four. Padding takes place by appending elements to the array. 5977 * <li>Clauses with all {@code null}s are disregarded. 5978 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 5979 * </ol> 5980 * <p> 5981 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 5982 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 5983 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 5984 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 5985 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 5986 * iteration variable type. 5987 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 5988 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 5989 * </ol> 5990 * <p> 5991 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 5992 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 5993 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 5994 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 5995 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 5996 * (These types will be checked in step 2, along with all the clause function types.) 5997 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 5998 * <li>All of the collected parameter lists must be effectively identical. 5999 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6000 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6001 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6002 * the "internal parameter list". 6003 * </ul> 6004 * <p> 6005 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6006 * <li>Examine fini function return types, disregarding omitted fini functions. 6007 * <li>If there are no fini functions, the loop return type is {@code void}. 6008 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6009 * type. 6010 * </ol> 6011 * <p> 6012 * <em>Step 1D: Check other types.</em><ol type="a"> 6013 * <li>There must be at least one non-omitted pred function. 6014 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6015 * </ol> 6016 * <p> 6017 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6018 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6019 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6020 * (Note that their parameter lists are already effectively identical to this list.) 6021 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6022 * effectively identical to the internal parameter list {@code (V... A...)}. 6023 * </ol> 6024 * <p> 6025 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6026 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6027 * type. 6028 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6029 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6030 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6031 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6032 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6033 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6034 * loop return type. 6035 * </ol> 6036 * <p> 6037 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6038 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6039 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6040 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6041 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6042 * pad out the end of the list. 6043 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6044 * </ol> 6045 * <p> 6046 * <em>Final observations.</em><ol type="a"> 6047 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6048 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6049 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6050 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6051 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6052 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6053 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6054 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6055 * </ol> 6056 * <p> 6057 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6058 * <ul> 6059 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6060 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6061 * (Only one {@code Pn} has to be non-{@code null}.) 6062 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6063 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6064 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6065 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6066 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6067 * the resulting loop handle's parameter types {@code (A...)}. 6068 * </ul> 6069 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6070 * which is natural if most of the loop computation happens in the steps. For some loops, 6071 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6072 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6073 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6074 * where the init functions will need the extra parameters. For such reasons, the rules for 6075 * determining these parameters are as symmetric as possible, across all clause parts. 6076 * In general, the loop parameters function as common invariant values across the whole 6077 * loop, while the iteration variables function as common variant values, or (if there is 6078 * no step function) as internal loop invariant temporaries. 6079 * <p> 6080 * <em>Loop execution.</em><ol type="a"> 6081 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6082 * every clause function. These locals are loop invariant. 6083 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6084 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6085 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6086 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6087 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6088 * (in argument order). 6089 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6090 * returns {@code false}. 6091 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6092 * sequence {@code (v...)} of loop variables. 6093 * The updated value is immediately visible to all subsequent function calls. 6094 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6095 * (of type {@code R}) is returned from the loop as a whole. 6096 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6097 * except by throwing an exception. 6098 * </ol> 6099 * <p> 6100 * <em>Usage tips.</em> 6101 * <ul> 6102 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6103 * sometimes a step function only needs to observe the current value of its own variable. 6104 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6105 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6106 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6107 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6108 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6109 * <li>If some of the clause functions are virtual methods on an instance, the instance 6110 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6111 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6112 * will be the first iteration variable value, and it will be easy to use virtual 6113 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6114 * </ul> 6115 * <p> 6116 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6117 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6118 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6119 * <blockquote><pre>{@code 6120 * V... init...(A...); 6121 * boolean pred...(V..., A...); 6122 * V... step...(V..., A...); 6123 * R fini...(V..., A...); 6124 * R loop(A... a) { 6125 * V... v... = init...(a...); 6126 * for (;;) { 6127 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6128 * v = s(v..., a...); 6129 * if (!p(v..., a...)) { 6130 * return f(v..., a...); 6131 * } 6132 * } 6133 * } 6134 * } 6135 * }</pre></blockquote> 6136 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6137 * to their full length, even though individual clause functions may neglect to take them all. 6138 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6139 * 6140 * @apiNote Example: 6141 * <blockquote><pre>{@code 6142 * // iterative implementation of the factorial function as a loop handle 6143 * static int one(int k) { return 1; } 6144 * static int inc(int i, int acc, int k) { return i + 1; } 6145 * static int mult(int i, int acc, int k) { return i * acc; } 6146 * static boolean pred(int i, int acc, int k) { return i < k; } 6147 * static int fin(int i, int acc, int k) { return acc; } 6148 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6149 * // null initializer for counter, should initialize to 0 6150 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6151 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6152 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6153 * assertEquals(120, loop.invoke(5)); 6154 * }</pre></blockquote> 6155 * The same example, dropping arguments and using combinators: 6156 * <blockquote><pre>{@code 6157 * // simplified implementation of the factorial function as a loop handle 6158 * static int inc(int i) { return i + 1; } // drop acc, k 6159 * static int mult(int i, int acc) { return i * acc; } //drop k 6160 * static boolean cmp(int i, int k) { return i < k; } 6161 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6162 * // null initializer for counter, should initialize to 0 6163 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6164 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6165 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6166 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6167 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6168 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6169 * assertEquals(720, loop.invoke(6)); 6170 * }</pre></blockquote> 6171 * A similar example, using a helper object to hold a loop parameter: 6172 * <blockquote><pre>{@code 6173 * // instance-based implementation of the factorial function as a loop handle 6174 * static class FacLoop { 6175 * final int k; 6176 * FacLoop(int k) { this.k = k; } 6177 * int inc(int i) { return i + 1; } 6178 * int mult(int i, int acc) { return i * acc; } 6179 * boolean pred(int i) { return i < k; } 6180 * int fin(int i, int acc) { return acc; } 6181 * } 6182 * // assume MH_FacLoop is a handle to the constructor 6183 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6184 * // null initializer for counter, should initialize to 0 6185 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6186 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6187 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6188 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6189 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6190 * assertEquals(5040, loop.invoke(7)); 6191 * }</pre></blockquote> 6192 * 6193 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6194 * 6195 * @return a method handle embodying the looping behavior as defined by the arguments. 6196 * 6197 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6198 * 6199 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6200 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6201 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6202 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6203 * @since 9 6204 */ 6205 public static MethodHandle loop(MethodHandle[]... clauses) { 6206 // Step 0: determine clause structure. 6207 loopChecks0(clauses); 6208 6209 List<MethodHandle> init = new ArrayList<>(); 6210 List<MethodHandle> step = new ArrayList<>(); 6211 List<MethodHandle> pred = new ArrayList<>(); 6212 List<MethodHandle> fini = new ArrayList<>(); 6213 6214 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6215 init.add(clause[0]); // all clauses have at least length 1 6216 step.add(clause.length <= 1 ? null : clause[1]); 6217 pred.add(clause.length <= 2 ? null : clause[2]); 6218 fini.add(clause.length <= 3 ? null : clause[3]); 6219 }); 6220 6221 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6222 final int nclauses = init.size(); 6223 6224 // Step 1A: determine iteration variables (V...). 6225 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6226 for (int i = 0; i < nclauses; ++i) { 6227 MethodHandle in = init.get(i); 6228 MethodHandle st = step.get(i); 6229 if (in == null && st == null) { 6230 iterationVariableTypes.add(void.class); 6231 } else if (in != null && st != null) { 6232 loopChecks1a(i, in, st); 6233 iterationVariableTypes.add(in.type().returnType()); 6234 } else { 6235 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6236 } 6237 } 6238 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). 6239 collect(Collectors.toList()); 6240 6241 // Step 1B: determine loop parameters (A...). 6242 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6243 loopChecks1b(init, commonSuffix); 6244 6245 // Step 1C: determine loop return type. 6246 // Step 1D: check other types. 6247 // local variable required here; see JDK-8223553 6248 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6249 .map(MethodType::returnType); 6250 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6251 loopChecks1cd(pred, fini, loopReturnType); 6252 6253 // Step 2: determine parameter lists. 6254 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6255 commonParameterSequence.addAll(commonSuffix); 6256 loopChecks2(step, pred, fini, commonParameterSequence); 6257 6258 // Step 3: fill in omitted functions. 6259 for (int i = 0; i < nclauses; ++i) { 6260 Class<?> t = iterationVariableTypes.get(i); 6261 if (init.get(i) == null) { 6262 init.set(i, empty(methodType(t, commonSuffix))); 6263 } 6264 if (step.get(i) == null) { 6265 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6266 } 6267 if (pred.get(i) == null) { 6268 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence)); 6269 } 6270 if (fini.get(i) == null) { 6271 fini.set(i, empty(methodType(t, commonParameterSequence))); 6272 } 6273 } 6274 6275 // Step 4: fill in missing parameter types. 6276 // Also convert all handles to fixed-arity handles. 6277 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6278 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6279 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6280 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6281 6282 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6283 allMatch(pl -> pl.equals(commonSuffix)); 6284 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6285 allMatch(pl -> pl.equals(commonParameterSequence)); 6286 6287 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6288 } 6289 6290 private static void loopChecks0(MethodHandle[][] clauses) { 6291 if (clauses == null || clauses.length == 0) { 6292 throw newIllegalArgumentException("null or no clauses passed"); 6293 } 6294 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6295 throw newIllegalArgumentException("null clauses are not allowed"); 6296 } 6297 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6298 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6299 } 6300 } 6301 6302 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6303 if (in.type().returnType() != st.type().returnType()) { 6304 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6305 st.type().returnType()); 6306 } 6307 } 6308 6309 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6310 final List<Class<?>> empty = List.of(); 6311 final List<Class<?>> longest = mhs.filter(Objects::nonNull). 6312 // take only those that can contribute to a common suffix because they are longer than the prefix 6313 map(MethodHandle::type). 6314 filter(t -> t.parameterCount() > skipSize). 6315 map(MethodType::parameterList). 6316 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 6317 return longest.size() == 0 ? empty : longest.subList(skipSize, longest.size()); 6318 } 6319 6320 private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) { 6321 final List<Class<?>> empty = List.of(); 6322 return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 6323 } 6324 6325 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6326 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6327 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6328 return longestParameterList(Arrays.asList(longest1, longest2)); 6329 } 6330 6331 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6332 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6333 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6334 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6335 " (common suffix: " + commonSuffix + ")"); 6336 } 6337 } 6338 6339 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6340 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6341 anyMatch(t -> t != loopReturnType)) { 6342 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6343 loopReturnType + ")"); 6344 } 6345 6346 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { 6347 throw newIllegalArgumentException("no predicate found", pred); 6348 } 6349 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6350 anyMatch(t -> t != boolean.class)) { 6351 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6352 } 6353 } 6354 6355 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6356 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6357 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6358 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6359 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6360 } 6361 } 6362 6363 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6364 return hs.stream().map(h -> { 6365 int pc = h.type().parameterCount(); 6366 int tpsize = targetParams.size(); 6367 return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h; 6368 }).collect(Collectors.toList()); 6369 } 6370 6371 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6372 return hs.stream().map(MethodHandle::asFixedArity).collect(Collectors.toList()); 6373 } 6374 6375 /** 6376 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6377 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6378 * <p> 6379 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6380 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6381 * evaluates to {@code true}). 6382 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6383 * <p> 6384 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6385 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6386 * and updated with the value returned from its invocation. The result of loop execution will be 6387 * the final value of the additional loop-local variable (if present). 6388 * <p> 6389 * The following rules hold for these argument handles:<ul> 6390 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6391 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6392 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6393 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6394 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6395 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6396 * It will constrain the parameter lists of the other loop parts. 6397 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6398 * list {@code (A...)} is called the <em>external parameter list</em>. 6399 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6400 * additional state variable of the loop. 6401 * The body must both accept and return a value of this type {@code V}. 6402 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6403 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6404 * <a href="MethodHandles.html#effid">effectively identical</a> 6405 * to the external parameter list {@code (A...)}. 6406 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6407 * {@linkplain #empty default value}. 6408 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6409 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6410 * effectively identical to the internal parameter list. 6411 * </ul> 6412 * <p> 6413 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6414 * <li>The loop handle's result type is the result type {@code V} of the body. 6415 * <li>The loop handle's parameter types are the types {@code (A...)}, 6416 * from the external parameter list. 6417 * </ul> 6418 * <p> 6419 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6420 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6421 * passed to the loop. 6422 * <blockquote><pre>{@code 6423 * V init(A...); 6424 * boolean pred(V, A...); 6425 * V body(V, A...); 6426 * V whileLoop(A... a...) { 6427 * V v = init(a...); 6428 * while (pred(v, a...)) { 6429 * v = body(v, a...); 6430 * } 6431 * return v; 6432 * } 6433 * }</pre></blockquote> 6434 * 6435 * @apiNote Example: 6436 * <blockquote><pre>{@code 6437 * // implement the zip function for lists as a loop handle 6438 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6439 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6440 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6441 * zip.add(a.next()); 6442 * zip.add(b.next()); 6443 * return zip; 6444 * } 6445 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6446 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6447 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6448 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6449 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6450 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6451 * }</pre></blockquote> 6452 * 6453 * 6454 * @apiNote The implementation of this method can be expressed as follows: 6455 * <blockquote><pre>{@code 6456 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6457 * MethodHandle fini = (body.type().returnType() == void.class 6458 * ? null : identity(body.type().returnType())); 6459 * MethodHandle[] 6460 * checkExit = { null, null, pred, fini }, 6461 * varBody = { init, body }; 6462 * return loop(checkExit, varBody); 6463 * } 6464 * }</pre></blockquote> 6465 * 6466 * @param init optional initializer, providing the initial value of the loop variable. 6467 * May be {@code null}, implying a default initial value. See above for other constraints. 6468 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6469 * above for other constraints. 6470 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6471 * See above for other constraints. 6472 * 6473 * @return a method handle implementing the {@code while} loop as described by the arguments. 6474 * @throws IllegalArgumentException if the rules for the arguments are violated. 6475 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6476 * 6477 * @see #loop(MethodHandle[][]) 6478 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6479 * @since 9 6480 */ 6481 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6482 whileLoopChecks(init, pred, body); 6483 MethodHandle fini = identityOrVoid(body.type().returnType()); 6484 MethodHandle[] checkExit = { null, null, pred, fini }; 6485 MethodHandle[] varBody = { init, body }; 6486 return loop(checkExit, varBody); 6487 } 6488 6489 /** 6490 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6491 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6492 * <p> 6493 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6494 * method will, in each iteration, first execute its body and then evaluate the predicate. 6495 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6496 * <p> 6497 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6498 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6499 * and updated with the value returned from its invocation. The result of loop execution will be 6500 * the final value of the additional loop-local variable (if present). 6501 * <p> 6502 * The following rules hold for these argument handles:<ul> 6503 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6504 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6505 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6506 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6507 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6508 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6509 * It will constrain the parameter lists of the other loop parts. 6510 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6511 * list {@code (A...)} is called the <em>external parameter list</em>. 6512 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6513 * additional state variable of the loop. 6514 * The body must both accept and return a value of this type {@code V}. 6515 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6516 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6517 * <a href="MethodHandles.html#effid">effectively identical</a> 6518 * to the external parameter list {@code (A...)}. 6519 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6520 * {@linkplain #empty default value}. 6521 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6522 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6523 * effectively identical to the internal parameter list. 6524 * </ul> 6525 * <p> 6526 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6527 * <li>The loop handle's result type is the result type {@code V} of the body. 6528 * <li>The loop handle's parameter types are the types {@code (A...)}, 6529 * from the external parameter list. 6530 * </ul> 6531 * <p> 6532 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6533 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6534 * passed to the loop. 6535 * <blockquote><pre>{@code 6536 * V init(A...); 6537 * boolean pred(V, A...); 6538 * V body(V, A...); 6539 * V doWhileLoop(A... a...) { 6540 * V v = init(a...); 6541 * do { 6542 * v = body(v, a...); 6543 * } while (pred(v, a...)); 6544 * return v; 6545 * } 6546 * }</pre></blockquote> 6547 * 6548 * @apiNote Example: 6549 * <blockquote><pre>{@code 6550 * // int i = 0; while (i < limit) { ++i; } return i; => limit 6551 * static int zero(int limit) { return 0; } 6552 * static int step(int i, int limit) { return i + 1; } 6553 * static boolean pred(int i, int limit) { return i < limit; } 6554 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 6555 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 6556 * assertEquals(23, loop.invoke(23)); 6557 * }</pre></blockquote> 6558 * 6559 * 6560 * @apiNote The implementation of this method can be expressed as follows: 6561 * <blockquote><pre>{@code 6562 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6563 * MethodHandle fini = (body.type().returnType() == void.class 6564 * ? null : identity(body.type().returnType())); 6565 * MethodHandle[] clause = { init, body, pred, fini }; 6566 * return loop(clause); 6567 * } 6568 * }</pre></blockquote> 6569 * 6570 * @param init optional initializer, providing the initial value of the loop variable. 6571 * May be {@code null}, implying a default initial value. See above for other constraints. 6572 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6573 * See above for other constraints. 6574 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6575 * above for other constraints. 6576 * 6577 * @return a method handle implementing the {@code while} loop as described by the arguments. 6578 * @throws IllegalArgumentException if the rules for the arguments are violated. 6579 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6580 * 6581 * @see #loop(MethodHandle[][]) 6582 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 6583 * @since 9 6584 */ 6585 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6586 whileLoopChecks(init, pred, body); 6587 MethodHandle fini = identityOrVoid(body.type().returnType()); 6588 MethodHandle[] clause = {init, body, pred, fini }; 6589 return loop(clause); 6590 } 6591 6592 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 6593 Objects.requireNonNull(pred); 6594 Objects.requireNonNull(body); 6595 MethodType bodyType = body.type(); 6596 Class<?> returnType = bodyType.returnType(); 6597 List<Class<?>> innerList = bodyType.parameterList(); 6598 List<Class<?>> outerList = innerList; 6599 if (returnType == void.class) { 6600 // OK 6601 } else if (innerList.size() == 0 || innerList.get(0) != returnType) { 6602 // leading V argument missing => error 6603 MethodType expected = bodyType.insertParameterTypes(0, returnType); 6604 throw misMatchedTypes("body function", bodyType, expected); 6605 } else { 6606 outerList = innerList.subList(1, innerList.size()); 6607 } 6608 MethodType predType = pred.type(); 6609 if (predType.returnType() != boolean.class || 6610 !predType.effectivelyIdenticalParameters(0, innerList)) { 6611 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 6612 } 6613 if (init != null) { 6614 MethodType initType = init.type(); 6615 if (initType.returnType() != returnType || 6616 !initType.effectivelyIdenticalParameters(0, outerList)) { 6617 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 6618 } 6619 } 6620 } 6621 6622 /** 6623 * Constructs a loop that runs a given number of iterations. 6624 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6625 * <p> 6626 * The number of iterations is determined by the {@code iterations} handle evaluation result. 6627 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 6628 * It will be initialized to 0 and incremented by 1 in each iteration. 6629 * <p> 6630 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 6631 * of that type is also present. This variable is initialized using the optional {@code init} handle, 6632 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 6633 * <p> 6634 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 6635 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 6636 * iteration variable. 6637 * The result of the loop handle execution will be the final {@code V} value of that variable 6638 * (or {@code void} if there is no {@code V} variable). 6639 * <p> 6640 * The following rules hold for the argument handles:<ul> 6641 * <li>The {@code iterations} handle must not be {@code null}, and must return 6642 * the type {@code int}, referred to here as {@code I} in parameter type lists. 6643 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6644 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 6645 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6646 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 6647 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 6648 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 6649 * of types called the <em>internal parameter list</em>. 6650 * It will constrain the parameter lists of the other loop parts. 6651 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 6652 * with no additional {@code A} types, then the internal parameter list is extended by 6653 * the argument types {@code A...} of the {@code iterations} handle. 6654 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 6655 * list {@code (A...)} is called the <em>external parameter list</em>. 6656 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6657 * additional state variable of the loop. 6658 * The body must both accept a leading parameter and return a value of this type {@code V}. 6659 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6660 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6661 * <a href="MethodHandles.html#effid">effectively identical</a> 6662 * to the external parameter list {@code (A...)}. 6663 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6664 * {@linkplain #empty default value}. 6665 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 6666 * effectively identical to the external parameter list {@code (A...)}. 6667 * </ul> 6668 * <p> 6669 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6670 * <li>The loop handle's result type is the result type {@code V} of the body. 6671 * <li>The loop handle's parameter types are the types {@code (A...)}, 6672 * from the external parameter list. 6673 * </ul> 6674 * <p> 6675 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6676 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 6677 * arguments passed to the loop. 6678 * <blockquote><pre>{@code 6679 * int iterations(A...); 6680 * V init(A...); 6681 * V body(V, int, A...); 6682 * V countedLoop(A... a...) { 6683 * int end = iterations(a...); 6684 * V v = init(a...); 6685 * for (int i = 0; i < end; ++i) { 6686 * v = body(v, i, a...); 6687 * } 6688 * return v; 6689 * } 6690 * }</pre></blockquote> 6691 * 6692 * @apiNote Example with a fully conformant body method: 6693 * <blockquote><pre>{@code 6694 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6695 * // => a variation on a well known theme 6696 * static String step(String v, int counter, String init) { return "na " + v; } 6697 * // assume MH_step is a handle to the method above 6698 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 6699 * MethodHandle start = MethodHandles.identity(String.class); 6700 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 6701 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 6702 * }</pre></blockquote> 6703 * 6704 * @apiNote Example with the simplest possible body method type, 6705 * and passing the number of iterations to the loop invocation: 6706 * <blockquote><pre>{@code 6707 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6708 * // => a variation on a well known theme 6709 * static String step(String v, int counter ) { return "na " + v; } 6710 * // assume MH_step is a handle to the method above 6711 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 6712 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 6713 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 6714 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 6715 * }</pre></blockquote> 6716 * 6717 * @apiNote Example that treats the number of iterations, string to append to, and string to append 6718 * as loop parameters: 6719 * <blockquote><pre>{@code 6720 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6721 * // => a variation on a well known theme 6722 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 6723 * // assume MH_step is a handle to the method above 6724 * MethodHandle count = MethodHandles.identity(int.class); 6725 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 6726 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 6727 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 6728 * }</pre></blockquote> 6729 * 6730 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 6731 * to enforce a loop type: 6732 * <blockquote><pre>{@code 6733 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6734 * // => a variation on a well known theme 6735 * static String step(String v, int counter, String pre) { return pre + " " + v; } 6736 * // assume MH_step is a handle to the method above 6737 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 6738 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 6739 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 6740 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 6741 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 6742 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 6743 * }</pre></blockquote> 6744 * 6745 * @apiNote The implementation of this method can be expressed as follows: 6746 * <blockquote><pre>{@code 6747 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 6748 * return countedLoop(empty(iterations.type()), iterations, init, body); 6749 * } 6750 * }</pre></blockquote> 6751 * 6752 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 6753 * result type must be {@code int}. See above for other constraints. 6754 * @param init optional initializer, providing the initial value of the loop variable. 6755 * May be {@code null}, implying a default initial value. See above for other constraints. 6756 * @param body body of the loop, which may not be {@code null}. 6757 * It controls the loop parameters and result type in the standard case (see above for details). 6758 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 6759 * and may accept any number of additional types. 6760 * See above for other constraints. 6761 * 6762 * @return a method handle representing the loop. 6763 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 6764 * @throws IllegalArgumentException if any argument violates the rules formulated above. 6765 * 6766 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 6767 * @since 9 6768 */ 6769 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 6770 return countedLoop(empty(iterations.type()), iterations, init, body); 6771 } 6772 6773 /** 6774 * Constructs a loop that counts over a range of numbers. 6775 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6776 * <p> 6777 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 6778 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 6779 * values of the loop counter. 6780 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 6781 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 6782 * <p> 6783 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 6784 * of that type is also present. This variable is initialized using the optional {@code init} handle, 6785 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 6786 * <p> 6787 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 6788 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 6789 * iteration variable. 6790 * The result of the loop handle execution will be the final {@code V} value of that variable 6791 * (or {@code void} if there is no {@code V} variable). 6792 * <p> 6793 * The following rules hold for the argument handles:<ul> 6794 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 6795 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 6796 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6797 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 6798 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6799 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 6800 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 6801 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 6802 * of types called the <em>internal parameter list</em>. 6803 * It will constrain the parameter lists of the other loop parts. 6804 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 6805 * with no additional {@code A} types, then the internal parameter list is extended by 6806 * the argument types {@code A...} of the {@code end} handle. 6807 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 6808 * list {@code (A...)} is called the <em>external parameter list</em>. 6809 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6810 * additional state variable of the loop. 6811 * The body must both accept a leading parameter and return a value of this type {@code V}. 6812 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6813 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6814 * <a href="MethodHandles.html#effid">effectively identical</a> 6815 * to the external parameter list {@code (A...)}. 6816 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6817 * {@linkplain #empty default value}. 6818 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 6819 * effectively identical to the external parameter list {@code (A...)}. 6820 * <li>Likewise, the parameter list of {@code end} must be effectively identical 6821 * to the external parameter list. 6822 * </ul> 6823 * <p> 6824 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6825 * <li>The loop handle's result type is the result type {@code V} of the body. 6826 * <li>The loop handle's parameter types are the types {@code (A...)}, 6827 * from the external parameter list. 6828 * </ul> 6829 * <p> 6830 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6831 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 6832 * arguments passed to the loop. 6833 * <blockquote><pre>{@code 6834 * int start(A...); 6835 * int end(A...); 6836 * V init(A...); 6837 * V body(V, int, A...); 6838 * V countedLoop(A... a...) { 6839 * int e = end(a...); 6840 * int s = start(a...); 6841 * V v = init(a...); 6842 * for (int i = s; i < e; ++i) { 6843 * v = body(v, i, a...); 6844 * } 6845 * return v; 6846 * } 6847 * }</pre></blockquote> 6848 * 6849 * @apiNote The implementation of this method can be expressed as follows: 6850 * <blockquote><pre>{@code 6851 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 6852 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 6853 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 6854 * // the following semantics: 6855 * // MH_increment: (int limit, int counter) -> counter + 1 6856 * // MH_predicate: (int limit, int counter) -> counter < limit 6857 * Class<?> counterType = start.type().returnType(); // int 6858 * Class<?> returnType = body.type().returnType(); 6859 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 6860 * if (returnType != void.class) { // ignore the V variable 6861 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 6862 * pred = dropArguments(pred, 1, returnType); // ditto 6863 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 6864 * } 6865 * body = dropArguments(body, 0, counterType); // ignore the limit variable 6866 * MethodHandle[] 6867 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 6868 * bodyClause = { init, body }, // v = init(); v = body(v, i) 6869 * indexVar = { start, incr }; // i = start(); i = i + 1 6870 * return loop(loopLimit, bodyClause, indexVar); 6871 * } 6872 * }</pre></blockquote> 6873 * 6874 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 6875 * See above for other constraints. 6876 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 6877 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 6878 * @param init optional initializer, providing the initial value of the loop variable. 6879 * May be {@code null}, implying a default initial value. See above for other constraints. 6880 * @param body body of the loop, which may not be {@code null}. 6881 * It controls the loop parameters and result type in the standard case (see above for details). 6882 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 6883 * and may accept any number of additional types. 6884 * See above for other constraints. 6885 * 6886 * @return a method handle representing the loop. 6887 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 6888 * @throws IllegalArgumentException if any argument violates the rules formulated above. 6889 * 6890 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 6891 * @since 9 6892 */ 6893 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 6894 countedLoopChecks(start, end, init, body); 6895 Class<?> counterType = start.type().returnType(); // int, but who's counting? 6896 Class<?> limitType = end.type().returnType(); // yes, int again 6897 Class<?> returnType = body.type().returnType(); 6898 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 6899 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 6900 MethodHandle retv = null; 6901 if (returnType != void.class) { 6902 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 6903 pred = dropArguments(pred, 1, returnType); // ditto 6904 retv = dropArguments(identity(returnType), 0, counterType); 6905 } 6906 body = dropArguments(body, 0, counterType); // ignore the limit variable 6907 MethodHandle[] 6908 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 6909 bodyClause = { init, body }, // v = init(); v = body(v, i) 6910 indexVar = { start, incr }; // i = start(); i = i + 1 6911 return loop(loopLimit, bodyClause, indexVar); 6912 } 6913 6914 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 6915 Objects.requireNonNull(start); 6916 Objects.requireNonNull(end); 6917 Objects.requireNonNull(body); 6918 Class<?> counterType = start.type().returnType(); 6919 if (counterType != int.class) { 6920 MethodType expected = start.type().changeReturnType(int.class); 6921 throw misMatchedTypes("start function", start.type(), expected); 6922 } else if (end.type().returnType() != counterType) { 6923 MethodType expected = end.type().changeReturnType(counterType); 6924 throw misMatchedTypes("end function", end.type(), expected); 6925 } 6926 MethodType bodyType = body.type(); 6927 Class<?> returnType = bodyType.returnType(); 6928 List<Class<?>> innerList = bodyType.parameterList(); 6929 // strip leading V value if present 6930 int vsize = (returnType == void.class ? 0 : 1); 6931 if (vsize != 0 && (innerList.size() == 0 || innerList.get(0) != returnType)) { 6932 // argument list has no "V" => error 6933 MethodType expected = bodyType.insertParameterTypes(0, returnType); 6934 throw misMatchedTypes("body function", bodyType, expected); 6935 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 6936 // missing I type => error 6937 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 6938 throw misMatchedTypes("body function", bodyType, expected); 6939 } 6940 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 6941 if (outerList.isEmpty()) { 6942 // special case; take lists from end handle 6943 outerList = end.type().parameterList(); 6944 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 6945 } 6946 MethodType expected = methodType(counterType, outerList); 6947 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 6948 throw misMatchedTypes("start parameter types", start.type(), expected); 6949 } 6950 if (end.type() != start.type() && 6951 !end.type().effectivelyIdenticalParameters(0, outerList)) { 6952 throw misMatchedTypes("end parameter types", end.type(), expected); 6953 } 6954 if (init != null) { 6955 MethodType initType = init.type(); 6956 if (initType.returnType() != returnType || 6957 !initType.effectivelyIdenticalParameters(0, outerList)) { 6958 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 6959 } 6960 } 6961 } 6962 6963 /** 6964 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 6965 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6966 * <p> 6967 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 6968 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 6969 * <p> 6970 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 6971 * of that type is also present. This variable is initialized using the optional {@code init} handle, 6972 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 6973 * <p> 6974 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 6975 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 6976 * iteration variable. 6977 * The result of the loop handle execution will be the final {@code V} value of that variable 6978 * (or {@code void} if there is no {@code V} variable). 6979 * <p> 6980 * The following rules hold for the argument handles:<ul> 6981 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6982 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 6983 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6984 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 6985 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 6986 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 6987 * of types called the <em>internal parameter list</em>. 6988 * It will constrain the parameter lists of the other loop parts. 6989 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 6990 * with no additional {@code A} types, then the internal parameter list is extended by 6991 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 6992 * single type {@code Iterable} is added and constitutes the {@code A...} list. 6993 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 6994 * list {@code (A...)} is called the <em>external parameter list</em>. 6995 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6996 * additional state variable of the loop. 6997 * The body must both accept a leading parameter and return a value of this type {@code V}. 6998 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6999 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7000 * <a href="MethodHandles.html#effid">effectively identical</a> 7001 * to the external parameter list {@code (A...)}. 7002 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7003 * {@linkplain #empty default value}. 7004 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7005 * type {@code java.util.Iterator} or a subtype thereof. 7006 * The iterator it produces when the loop is executed will be assumed 7007 * to yield values which can be converted to type {@code T}. 7008 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7009 * effectively identical to the external parameter list {@code (A...)}. 7010 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7011 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7012 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7013 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7014 * the {@link MethodHandle#asType asType} conversion method. 7015 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7016 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7017 * </ul> 7018 * <p> 7019 * The type {@code T} may be either a primitive or reference. 7020 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7021 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7022 * as if by the {@link MethodHandle#asType asType} conversion method. 7023 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7024 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7025 * <p> 7026 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7027 * <li>The loop handle's result type is the result type {@code V} of the body. 7028 * <li>The loop handle's parameter types are the types {@code (A...)}, 7029 * from the external parameter list. 7030 * </ul> 7031 * <p> 7032 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7033 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7034 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7035 * <blockquote><pre>{@code 7036 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7037 * V init(A...); 7038 * V body(V,T,A...); 7039 * V iteratedLoop(A... a...) { 7040 * Iterator<T> it = iterator(a...); 7041 * V v = init(a...); 7042 * while (it.hasNext()) { 7043 * T t = it.next(); 7044 * v = body(v, t, a...); 7045 * } 7046 * return v; 7047 * } 7048 * }</pre></blockquote> 7049 * 7050 * @apiNote Example: 7051 * <blockquote><pre>{@code 7052 * // get an iterator from a list 7053 * static List<String> reverseStep(List<String> r, String e) { 7054 * r.add(0, e); 7055 * return r; 7056 * } 7057 * static List<String> newArrayList() { return new ArrayList<>(); } 7058 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7059 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7060 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7061 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7062 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7063 * }</pre></blockquote> 7064 * 7065 * @apiNote The implementation of this method can be expressed approximately as follows: 7066 * <blockquote><pre>{@code 7067 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7068 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7069 * Class<?> returnType = body.type().returnType(); 7070 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7071 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7072 * MethodHandle retv = null, step = body, startIter = iterator; 7073 * if (returnType != void.class) { 7074 * // the simple thing first: in (I V A...), drop the I to get V 7075 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7076 * // body type signature (V T A...), internal loop types (I V A...) 7077 * step = swapArguments(body, 0, 1); // swap V <-> T 7078 * } 7079 * if (startIter == null) startIter = MH_getIter; 7080 * MethodHandle[] 7081 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7082 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7083 * return loop(iterVar, bodyClause); 7084 * } 7085 * }</pre></blockquote> 7086 * 7087 * @param iterator an optional handle to return the iterator to start the loop. 7088 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7089 * See above for other constraints. 7090 * @param init optional initializer, providing the initial value of the loop variable. 7091 * May be {@code null}, implying a default initial value. See above for other constraints. 7092 * @param body body of the loop, which may not be {@code null}. 7093 * It controls the loop parameters and result type in the standard case (see above for details). 7094 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7095 * and may accept any number of additional types. 7096 * See above for other constraints. 7097 * 7098 * @return a method handle embodying the iteration loop functionality. 7099 * @throws NullPointerException if the {@code body} handle is {@code null}. 7100 * @throws IllegalArgumentException if any argument violates the above requirements. 7101 * 7102 * @since 9 7103 */ 7104 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7105 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7106 Class<?> returnType = body.type().returnType(); 7107 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7108 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7109 MethodHandle startIter; 7110 MethodHandle nextVal; 7111 { 7112 MethodType iteratorType; 7113 if (iterator == null) { 7114 // derive argument type from body, if available, else use Iterable 7115 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7116 iteratorType = startIter.type().changeParameterType(0, iterableType); 7117 } else { 7118 // force return type to the internal iterator class 7119 iteratorType = iterator.type().changeReturnType(Iterator.class); 7120 startIter = iterator; 7121 } 7122 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7123 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7124 7125 // perform the asType transforms under an exception transformer, as per spec.: 7126 try { 7127 startIter = startIter.asType(iteratorType); 7128 nextVal = nextRaw.asType(nextValType); 7129 } catch (WrongMethodTypeException ex) { 7130 throw new IllegalArgumentException(ex); 7131 } 7132 } 7133 7134 MethodHandle retv = null, step = body; 7135 if (returnType != void.class) { 7136 // the simple thing first: in (I V A...), drop the I to get V 7137 retv = dropArguments(identity(returnType), 0, Iterator.class); 7138 // body type signature (V T A...), internal loop types (I V A...) 7139 step = swapArguments(body, 0, 1); // swap V <-> T 7140 } 7141 7142 MethodHandle[] 7143 iterVar = { startIter, null, hasNext, retv }, 7144 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7145 return loop(iterVar, bodyClause); 7146 } 7147 7148 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7149 Objects.requireNonNull(body); 7150 MethodType bodyType = body.type(); 7151 Class<?> returnType = bodyType.returnType(); 7152 List<Class<?>> internalParamList = bodyType.parameterList(); 7153 // strip leading V value if present 7154 int vsize = (returnType == void.class ? 0 : 1); 7155 if (vsize != 0 && (internalParamList.size() == 0 || internalParamList.get(0) != returnType)) { 7156 // argument list has no "V" => error 7157 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7158 throw misMatchedTypes("body function", bodyType, expected); 7159 } else if (internalParamList.size() <= vsize) { 7160 // missing T type => error 7161 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7162 throw misMatchedTypes("body function", bodyType, expected); 7163 } 7164 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7165 Class<?> iterableType = null; 7166 if (iterator != null) { 7167 // special case; if the body handle only declares V and T then 7168 // the external parameter list is obtained from iterator handle 7169 if (externalParamList.isEmpty()) { 7170 externalParamList = iterator.type().parameterList(); 7171 } 7172 MethodType itype = iterator.type(); 7173 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7174 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7175 } 7176 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7177 MethodType expected = methodType(itype.returnType(), externalParamList); 7178 throw misMatchedTypes("iterator parameters", itype, expected); 7179 } 7180 } else { 7181 if (externalParamList.isEmpty()) { 7182 // special case; if the iterator handle is null and the body handle 7183 // only declares V and T then the external parameter list consists 7184 // of Iterable 7185 externalParamList = Arrays.asList(Iterable.class); 7186 iterableType = Iterable.class; 7187 } else { 7188 // special case; if the iterator handle is null and the external 7189 // parameter list is not empty then the first parameter must be 7190 // assignable to Iterable 7191 iterableType = externalParamList.get(0); 7192 if (!Iterable.class.isAssignableFrom(iterableType)) { 7193 throw newIllegalArgumentException( 7194 "inferred first loop argument must inherit from Iterable: " + iterableType); 7195 } 7196 } 7197 } 7198 if (init != null) { 7199 MethodType initType = init.type(); 7200 if (initType.returnType() != returnType || 7201 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7202 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7203 } 7204 } 7205 return iterableType; // help the caller a bit 7206 } 7207 7208 /*non-public*/ 7209 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7210 // there should be a better way to uncross my wires 7211 int arity = mh.type().parameterCount(); 7212 int[] order = new int[arity]; 7213 for (int k = 0; k < arity; k++) order[k] = k; 7214 order[i] = j; order[j] = i; 7215 Class<?>[] types = mh.type().parameterArray(); 7216 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7217 MethodType swapType = methodType(mh.type().returnType(), types); 7218 return permuteArguments(mh, swapType, order); 7219 } 7220 7221 /** 7222 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7223 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7224 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7225 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7226 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7227 * {@code try-finally} handle. 7228 * <p> 7229 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7230 * The first is the exception thrown during the 7231 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7232 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7233 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7234 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7235 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7236 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7237 * <p> 7238 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7239 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7240 * two extra leading parameters:<ul> 7241 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7242 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7243 * the result from the execution of the {@code target} handle. 7244 * This parameter is not present if the {@code target} returns {@code void}. 7245 * </ul> 7246 * <p> 7247 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7248 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7249 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7250 * the cleanup. 7251 * <blockquote><pre>{@code 7252 * V target(A..., B...); 7253 * V cleanup(Throwable, V, A...); 7254 * V adapter(A... a, B... b) { 7255 * V result = (zero value for V); 7256 * Throwable throwable = null; 7257 * try { 7258 * result = target(a..., b...); 7259 * } catch (Throwable t) { 7260 * throwable = t; 7261 * throw t; 7262 * } finally { 7263 * result = cleanup(throwable, result, a...); 7264 * } 7265 * return result; 7266 * } 7267 * }</pre></blockquote> 7268 * <p> 7269 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7270 * be modified by execution of the target, and so are passed unchanged 7271 * from the caller to the cleanup, if it is invoked. 7272 * <p> 7273 * The target and cleanup must return the same type, even if the cleanup 7274 * always throws. 7275 * To create such a throwing cleanup, compose the cleanup logic 7276 * with {@link #throwException throwException}, 7277 * in order to create a method handle of the correct return type. 7278 * <p> 7279 * Note that {@code tryFinally} never converts exceptions into normal returns. 7280 * In rare cases where exceptions must be converted in that way, first wrap 7281 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7282 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7283 * <p> 7284 * It is recommended that the first parameter type of {@code cleanup} be 7285 * declared {@code Throwable} rather than a narrower subtype. This ensures 7286 * {@code cleanup} will always be invoked with whatever exception that 7287 * {@code target} throws. Declaring a narrower type may result in a 7288 * {@code ClassCastException} being thrown by the {@code try-finally} 7289 * handle if the type of the exception thrown by {@code target} is not 7290 * assignable to the first parameter type of {@code cleanup}. Note that 7291 * various exception types of {@code VirtualMachineError}, 7292 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7293 * thrown by almost any kind of Java code, and a finally clause that 7294 * catches (say) only {@code IOException} would mask any of the others 7295 * behind a {@code ClassCastException}. 7296 * 7297 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7298 * @param cleanup the handle that is invoked in the finally block. 7299 * 7300 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7301 * @throws NullPointerException if any argument is null 7302 * @throws IllegalArgumentException if {@code cleanup} does not accept 7303 * the required leading arguments, or if the method handle types do 7304 * not match in their return types and their 7305 * corresponding trailing parameters 7306 * 7307 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7308 * @since 9 7309 */ 7310 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7311 List<Class<?>> targetParamTypes = target.type().parameterList(); 7312 Class<?> rtype = target.type().returnType(); 7313 7314 tryFinallyChecks(target, cleanup); 7315 7316 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7317 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7318 // target parameter list. 7319 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); 7320 7321 // Ensure that the intrinsic type checks the instance thrown by the 7322 // target against the first parameter of cleanup 7323 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7324 7325 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7326 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7327 } 7328 7329 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7330 Class<?> rtype = target.type().returnType(); 7331 if (rtype != cleanup.type().returnType()) { 7332 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7333 } 7334 MethodType cleanupType = cleanup.type(); 7335 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7336 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7337 } 7338 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7339 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7340 } 7341 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7342 // target parameter list. 7343 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7344 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7345 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7346 cleanup.type(), target.type()); 7347 } 7348 } 7349 7350 }