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