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