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