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