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