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