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