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