1 /* 2 * Copyright (c) 2008, 2016, 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.org.objectweb.asm.ClassWriter; 29 import jdk.internal.org.objectweb.asm.Opcodes; 30 import jdk.internal.reflect.CallerSensitive; 31 import jdk.internal.reflect.Reflection; 32 import sun.invoke.util.ValueConversions; 33 import sun.invoke.util.VerifyAccess; 34 import sun.invoke.util.Wrapper; 35 import sun.reflect.misc.ReflectUtil; 36 import sun.security.util.SecurityConstants; 37 38 import java.lang.invoke.LambdaForm.BasicType; 39 import java.lang.reflect.Constructor; 40 import java.lang.reflect.Field; 41 import java.lang.reflect.Member; 42 import java.lang.reflect.Method; 43 import java.lang.reflect.Modifier; 44 import java.lang.reflect.ReflectPermission; 45 import java.nio.ByteOrder; 46 import java.security.AccessController; 47 import java.security.PrivilegedAction; 48 import java.util.ArrayList; 49 import java.util.Arrays; 50 import java.util.BitSet; 51 import java.util.Iterator; 52 import java.util.List; 53 import java.util.Objects; 54 import java.util.concurrent.ConcurrentHashMap; 55 import java.util.stream.Collectors; 56 import java.util.stream.Stream; 57 58 import static java.lang.invoke.MethodHandleImpl.Intrinsic; 59 import static java.lang.invoke.MethodHandleNatives.Constants.*; 60 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 61 import static java.lang.invoke.MethodType.methodType; 62 63 /** 64 * This class consists exclusively of static methods that operate on or return 65 * method handles. They fall into several categories: 66 * <ul> 67 * <li>Lookup methods which help create method handles for methods and fields. 68 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 69 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 70 * </ul> 71 * 72 * @author John Rose, JSR 292 EG 73 * @since 1.7 74 */ 75 public class MethodHandles { 76 77 private MethodHandles() { } // do not instantiate 78 79 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 80 81 // See IMPL_LOOKUP below. 82 83 //// Method handle creation from ordinary methods. 84 85 /** 86 * Returns a {@link Lookup lookup object} with 87 * full capabilities to emulate all supported bytecode behaviors of the caller. 88 * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller. 89 * Factory methods on the lookup object can create 90 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 91 * for any member that the caller has access to via bytecodes, 92 * including protected and private fields and methods. 93 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 94 * Do not store it in place where untrusted code can access it. 95 * <p> 96 * This method is caller sensitive, which means that it may return different 97 * values to different callers. 98 * <p> 99 * For any given caller class {@code C}, the lookup object returned by this call 100 * has equivalent capabilities to any lookup object 101 * supplied by the JVM to the bootstrap method of an 102 * <a href="package-summary.html#indyinsn">invokedynamic instruction</a> 103 * executing in the same caller class {@code C}. 104 * @return a lookup object for the caller of this method, with private access 105 */ 106 @CallerSensitive 107 public static Lookup lookup() { 108 return new Lookup(Reflection.getCallerClass()); 109 } 110 111 /** 112 * Returns a {@link Lookup lookup object} which is trusted minimally. 113 * It can only be used to create method handles to public members in 114 * public classes in packages that are exported unconditionally. 115 * <p> 116 * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup 117 * object is in an unnamed module. 118 * Consequently, the lookup context of this lookup object will be the bootstrap 119 * class loader, which means it cannot find user classes. 120 * 121 * <p style="font-size:smaller;"> 122 * <em>Discussion:</em> 123 * The lookup class can be changed to any other class {@code C} using an expression of the form 124 * {@link Lookup#in publicLookup().in(C.class)}. 125 * but may change the lookup context by virtue of changing the class loader. 126 * A public lookup object is always subject to 127 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 128 * Also, it cannot access 129 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 130 * @return a lookup object which is trusted minimally 131 */ 132 public static Lookup publicLookup() { 133 // During VM startup then only classes in the java.base module can be 134 // loaded and linked. This is because java.base exports aren't setup until 135 // the module system is initialized, hence types in the unnamed module 136 // (or any named module) can't link to java/lang/Object. 137 if (!jdk.internal.misc.VM.isModuleSystemInited()) { 138 return new Lookup(Object.class, Lookup.PUBLIC); 139 } else { 140 return LookupHelper.PUBLIC_LOOKUP; 141 } 142 } 143 144 /** 145 * Performs an unchecked "crack" of a 146 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 147 * The result is as if the user had obtained a lookup object capable enough 148 * to crack the target method handle, called 149 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 150 * on the target to obtain its symbolic reference, and then called 151 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 152 * to resolve the symbolic reference to a member. 153 * <p> 154 * If there is a security manager, its {@code checkPermission} method 155 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 156 * @param <T> the desired type of the result, either {@link Member} or a subtype 157 * @param target a direct method handle to crack into symbolic reference components 158 * @param expected a class object representing the desired result type {@code T} 159 * @return a reference to the method, constructor, or field object 160 * @exception SecurityException if the caller is not privileged to call {@code setAccessible} 161 * @exception NullPointerException if either argument is {@code null} 162 * @exception IllegalArgumentException if the target is not a direct method handle 163 * @exception ClassCastException if the member is not of the expected type 164 * @since 1.8 165 */ 166 public static <T extends Member> T 167 reflectAs(Class<T> expected, MethodHandle target) { 168 SecurityManager smgr = System.getSecurityManager(); 169 if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION); 170 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 171 return lookup.revealDirect(target).reflectAs(expected, lookup); 172 } 173 // Copied from AccessibleObject, as used by Method.setAccessible, etc.: 174 private static final java.security.Permission ACCESS_PERMISSION = 175 new ReflectPermission("suppressAccessChecks"); 176 177 /** 178 * A <em>lookup object</em> is a factory for creating method handles, 179 * when the creation requires access checking. 180 * Method handles do not perform 181 * access checks when they are called, but rather when they are created. 182 * Therefore, method handle access 183 * restrictions must be enforced when a method handle is created. 184 * The caller class against which those restrictions are enforced 185 * is known as the {@linkplain #lookupClass lookup class}. 186 * <p> 187 * A lookup class which needs to create method handles will call 188 * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself. 189 * When the {@code Lookup} factory object is created, the identity of the lookup class is 190 * determined, and securely stored in the {@code Lookup} object. 191 * The lookup class (or its delegates) may then use factory methods 192 * on the {@code Lookup} object to create method handles for access-checked members. 193 * This includes all methods, constructors, and fields which are allowed to the lookup class, 194 * even private ones. 195 * 196 * <h1><a name="lookups"></a>Lookup Factory Methods</h1> 197 * The factory methods on a {@code Lookup} object correspond to all major 198 * use cases for methods, constructors, and fields. 199 * Each method handle created by a factory method is the functional 200 * equivalent of a particular <em>bytecode behavior</em>. 201 * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.) 202 * Here is a summary of the correspondence between these factory methods and 203 * the behavior of the resulting method handles: 204 * <table border=1 cellpadding=5 summary="lookup method behaviors"> 205 * <tr> 206 * <th><a name="equiv"></a>lookup expression</th> 207 * <th>member</th> 208 * <th>bytecode behavior</th> 209 * </tr> 210 * <tr> 211 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td> 212 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 213 * </tr> 214 * <tr> 215 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td> 216 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td> 217 * </tr> 218 * <tr> 219 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td> 220 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 221 * </tr> 222 * <tr> 223 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td> 224 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 225 * </tr> 226 * <tr> 227 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td> 228 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 229 * </tr> 230 * <tr> 231 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td> 232 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 233 * </tr> 234 * <tr> 235 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td> 236 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 237 * </tr> 238 * <tr> 239 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td> 240 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 241 * </tr> 242 * <tr> 243 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td> 244 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 245 * </tr> 246 * <tr> 247 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td> 248 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 249 * </tr> 250 * <tr> 251 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 252 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 253 * </tr> 254 * <tr> 255 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td> 256 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 257 * </tr> 258 * <tr> 259 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 260 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 261 * </tr> 262 * <tr> 263 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td> 264 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 265 * </tr> 266 * </table> 267 * 268 * Here, the type {@code C} is the class or interface being searched for a member, 269 * documented as a parameter named {@code refc} in the lookup methods. 270 * The method type {@code MT} is composed from the return type {@code T} 271 * and the sequence of argument types {@code A*}. 272 * The constructor also has a sequence of argument types {@code A*} and 273 * is deemed to return the newly-created object of type {@code C}. 274 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 275 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 276 * if it is present, it is always the leading argument to the method handle invocation. 277 * (In the case of some {@code protected} members, {@code this} may be 278 * restricted in type to the lookup class; see below.) 279 * The name {@code arg} stands for all the other method handle arguments. 280 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 281 * stands for a null reference if the accessed method or field is static, 282 * and {@code this} otherwise. 283 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 284 * for reflective objects corresponding to the given members. 285 * <p> 286 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 287 * as if by {@code ldc CONSTANT_Class}. 288 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 289 * <p> 290 * In cases where the given member is of variable arity (i.e., a method or constructor) 291 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 292 * In all other cases, the returned method handle will be of fixed arity. 293 * <p style="font-size:smaller;"> 294 * <em>Discussion:</em> 295 * The equivalence between looked-up method handles and underlying 296 * class members and bytecode behaviors 297 * can break down in a few ways: 298 * <ul style="font-size:smaller;"> 299 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 300 * the lookup can still succeed, even when there is no equivalent 301 * Java expression or bytecoded constant. 302 * <li>Likewise, if {@code T} or {@code MT} 303 * is not symbolically accessible from the lookup class's loader, 304 * the lookup can still succeed. 305 * For example, lookups for {@code MethodHandle.invokeExact} and 306 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 307 * <li>If there is a security manager installed, it can forbid the lookup 308 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 309 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 310 * constant is not subject to security manager checks. 311 * <li>If the looked-up method has a 312 * <a href="MethodHandle.html#maxarity">very large arity</a>, 313 * the method handle creation may fail, due to the method handle 314 * type having too many parameters. 315 * </ul> 316 * 317 * <h1><a name="access"></a>Access checking</h1> 318 * Access checks are applied in the factory methods of {@code Lookup}, 319 * when a method handle is created. 320 * This is a key difference from the Core Reflection API, since 321 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 322 * performs access checking against every caller, on every call. 323 * <p> 324 * All access checks start from a {@code Lookup} object, which 325 * compares its recorded lookup class against all requests to 326 * create method handles. 327 * A single {@code Lookup} object can be used to create any number 328 * of access-checked method handles, all checked against a single 329 * lookup class. 330 * <p> 331 * A {@code Lookup} object can be shared with other trusted code, 332 * such as a metaobject protocol. 333 * A shared {@code Lookup} object delegates the capability 334 * to create method handles on private members of the lookup class. 335 * Even if privileged code uses the {@code Lookup} object, 336 * the access checking is confined to the privileges of the 337 * original lookup class. 338 * <p> 339 * A lookup can fail, because 340 * the containing class is not accessible to the lookup class, or 341 * because the desired class member is missing, or because the 342 * desired class member is not accessible to the lookup class, or 343 * because the lookup object is not trusted enough to access the member. 344 * In any of these cases, a {@code ReflectiveOperationException} will be 345 * thrown from the attempted lookup. The exact class will be one of 346 * the following: 347 * <ul> 348 * <li>NoSuchMethodException — if a method is requested but does not exist 349 * <li>NoSuchFieldException — if a field is requested but does not exist 350 * <li>IllegalAccessException — if the member exists but an access check fails 351 * </ul> 352 * <p> 353 * In general, the conditions under which a method handle may be 354 * looked up for a method {@code M} are no more restrictive than the conditions 355 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 356 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 357 * a method handle lookup will generally raise a corresponding 358 * checked exception, such as {@code NoSuchMethodException}. 359 * And the effect of invoking the method handle resulting from the lookup 360 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 361 * to executing the compiled, verified, and resolved call to {@code M}. 362 * The same point is true of fields and constructors. 363 * <p style="font-size:smaller;"> 364 * <em>Discussion:</em> 365 * Access checks only apply to named and reflected methods, 366 * constructors, and fields. 367 * Other method handle creation methods, such as 368 * {@link MethodHandle#asType MethodHandle.asType}, 369 * do not require any access checks, and are used 370 * independently of any {@code Lookup} object. 371 * <p> 372 * If the desired member is {@code protected}, the usual JVM rules apply, 373 * including the requirement that the lookup class must be either be in the 374 * same package as the desired member, or must inherit that member. 375 * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.) 376 * In addition, if the desired member is a non-static field or method 377 * in a different package, the resulting method handle may only be applied 378 * to objects of the lookup class or one of its subclasses. 379 * This requirement is enforced by narrowing the type of the leading 380 * {@code this} parameter from {@code C} 381 * (which will necessarily be a superclass of the lookup class) 382 * to the lookup class itself. 383 * <p> 384 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 385 * that the receiver argument must match both the resolved method <em>and</em> 386 * the current class. Again, this requirement is enforced by narrowing the 387 * type of the leading parameter to the resulting method handle. 388 * (See the Java Virtual Machine Specification, section 4.10.1.9.) 389 * <p> 390 * The JVM represents constructors and static initializer blocks as internal methods 391 * with special names ({@code "<init>"} and {@code "<clinit>"}). 392 * The internal syntax of invocation instructions allows them to refer to such internal 393 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 394 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 395 * <p> 396 * In some cases, access between nested classes is obtained by the Java compiler by creating 397 * an wrapper method to access a private method of another class 398 * in the same top-level declaration. 399 * For example, a nested class {@code C.D} 400 * can access private members within other related classes such as 401 * {@code C}, {@code C.D.E}, or {@code C.B}, 402 * but the Java compiler may need to generate wrapper methods in 403 * those related classes. In such cases, a {@code Lookup} object on 404 * {@code C.E} would be unable to those private members. 405 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 406 * which can transform a lookup on {@code C.E} into one on any of those other 407 * classes, without special elevation of privilege. 408 * <p> 409 * The accesses permitted to a given lookup object may be limited, 410 * according to its set of {@link #lookupModes lookupModes}, 411 * to a subset of members normally accessible to the lookup class. 412 * For example, the {@link MethodHandles#publicLookup publicLookup} 413 * method produces a lookup object which is only allowed to access 414 * public members in public classes of exported packages. 415 * The caller sensitive method {@link MethodHandles#lookup lookup} 416 * produces a lookup object with full capabilities relative to 417 * its caller class, to emulate all supported bytecode behaviors. 418 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 419 * with fewer access modes than the original lookup object. 420 * 421 * <p style="font-size:smaller;"> 422 * <a name="privacc"></a> 423 * <em>Discussion of private access:</em> 424 * We say that a lookup has <em>private access</em> 425 * if its {@linkplain #lookupModes lookup modes} 426 * include the possibility of accessing {@code private} members. 427 * As documented in the relevant methods elsewhere, 428 * only lookups with private access possess the following capabilities: 429 * <ul style="font-size:smaller;"> 430 * <li>access private fields, methods, and constructors of the lookup class 431 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 432 * such as {@code Class.forName} 433 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 434 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 435 * for classes accessible to the lookup class 436 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 437 * within the same package member 438 * </ul> 439 * <p style="font-size:smaller;"> 440 * Each of these permissions is a consequence of the fact that a lookup object 441 * with private access can be securely traced back to an originating class, 442 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 443 * can be reliably determined and emulated by method handles. 444 * 445 * <h1><a name="secmgr"></a>Security manager interactions</h1> 446 * Although bytecode instructions can only refer to classes in 447 * a related class loader, this API can search for methods in any 448 * class, as long as a reference to its {@code Class} object is 449 * available. Such cross-loader references are also possible with the 450 * Core Reflection API, and are impossible to bytecode instructions 451 * such as {@code invokestatic} or {@code getfield}. 452 * There is a {@linkplain java.lang.SecurityManager security manager API} 453 * to allow applications to check such cross-loader references. 454 * These checks apply to both the {@code MethodHandles.Lookup} API 455 * and the Core Reflection API 456 * (as found on {@link java.lang.Class Class}). 457 * <p> 458 * If a security manager is present, member and class lookups are subject to 459 * additional checks. 460 * From one to three calls are made to the security manager. 461 * Any of these calls can refuse access by throwing a 462 * {@link java.lang.SecurityException SecurityException}. 463 * Define {@code smgr} as the security manager, 464 * {@code lookc} as the lookup class of the current lookup object, 465 * {@code refc} as the containing class in which the member 466 * is being sought, and {@code defc} as the class in which the 467 * member is actually defined. 468 * (If a class or other type is being accessed, 469 * the {@code refc} and {@code defc} values are the class itself.) 470 * The value {@code lookc} is defined as <em>not present</em> 471 * if the current lookup object does not have 472 * <a href="MethodHandles.Lookup.html#privacc">private access</a>. 473 * The calls are made according to the following rules: 474 * <ul> 475 * <li><b>Step 1:</b> 476 * If {@code lookc} is not present, or if its class loader is not 477 * the same as or an ancestor of the class loader of {@code refc}, 478 * then {@link SecurityManager#checkPackageAccess 479 * smgr.checkPackageAccess(refcPkg)} is called, 480 * where {@code refcPkg} is the package of {@code refc}. 481 * <li><b>Step 2a:</b> 482 * If the retrieved member is not public and 483 * {@code lookc} is not present, then 484 * {@link SecurityManager#checkPermission smgr.checkPermission} 485 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 486 * <li><b>Step 2b:</b> 487 * If the retrieved class has a {@code null} class loader, 488 * and {@code lookc} is not present, then 489 * {@link SecurityManager#checkPermission smgr.checkPermission} 490 * with {@code RuntimePermission("getClassLoader")} is called. 491 * <li><b>Step 3:</b> 492 * If the retrieved member is not public, 493 * and if {@code lookc} is not present, 494 * and if {@code defc} and {@code refc} are different, 495 * then {@link SecurityManager#checkPackageAccess 496 * smgr.checkPackageAccess(defcPkg)} is called, 497 * where {@code defcPkg} is the package of {@code defc}. 498 * </ul> 499 * Security checks are performed after other access checks have passed. 500 * Therefore, the above rules presuppose a member or class that is public, 501 * or else that is being accessed from a lookup class that has 502 * rights to access the member or class. 503 * 504 * <h1><a name="callsens"></a>Caller sensitive methods</h1> 505 * A small number of Java methods have a special property called caller sensitivity. 506 * A <em>caller-sensitive</em> method can behave differently depending on the 507 * identity of its immediate caller. 508 * <p> 509 * If a method handle for a caller-sensitive method is requested, 510 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 511 * but they take account of the lookup class in a special way. 512 * The resulting method handle behaves as if it were called 513 * from an instruction contained in the lookup class, 514 * so that the caller-sensitive method detects the lookup class. 515 * (By contrast, the invoker of the method handle is disregarded.) 516 * Thus, in the case of caller-sensitive methods, 517 * different lookup classes may give rise to 518 * differently behaving method handles. 519 * <p> 520 * In cases where the lookup object is 521 * {@link MethodHandles#publicLookup() publicLookup()}, 522 * or some other lookup object without 523 * <a href="MethodHandles.Lookup.html#privacc">private access</a>, 524 * the lookup class is disregarded. 525 * In such cases, no caller-sensitive method handle can be created, 526 * access is forbidden, and the lookup fails with an 527 * {@code IllegalAccessException}. 528 * <p style="font-size:smaller;"> 529 * <em>Discussion:</em> 530 * For example, the caller-sensitive method 531 * {@link java.lang.Class#forName(String) Class.forName(x)} 532 * can return varying classes or throw varying exceptions, 533 * depending on the class loader of the class that calls it. 534 * A public lookup of {@code Class.forName} will fail, because 535 * there is no reasonable way to determine its bytecode behavior. 536 * <p style="font-size:smaller;"> 537 * If an application caches method handles for broad sharing, 538 * it should use {@code publicLookup()} to create them. 539 * If there is a lookup of {@code Class.forName}, it will fail, 540 * and the application must take appropriate action in that case. 541 * It may be that a later lookup, perhaps during the invocation of a 542 * bootstrap method, can incorporate the specific identity 543 * of the caller, making the method accessible. 544 * <p style="font-size:smaller;"> 545 * The function {@code MethodHandles.lookup} is caller sensitive 546 * so that there can be a secure foundation for lookups. 547 * Nearly all other methods in the JSR 292 API rely on lookup 548 * objects to check access requests. 549 */ 550 public static final 551 class Lookup { 552 /** The class on behalf of whom the lookup is being performed. */ 553 private final Class<?> lookupClass; 554 555 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 556 private final int allowedModes; 557 558 /** A single-bit mask representing {@code public} access, 559 * which may contribute to the result of {@link #lookupModes lookupModes}. 560 * The value, {@code 0x01}, happens to be the same as the value of the 561 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 562 */ 563 public static final int PUBLIC = Modifier.PUBLIC; 564 565 /** A single-bit mask representing {@code private} access, 566 * which may contribute to the result of {@link #lookupModes lookupModes}. 567 * The value, {@code 0x02}, happens to be the same as the value of the 568 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 569 */ 570 public static final int PRIVATE = Modifier.PRIVATE; 571 572 /** A single-bit mask representing {@code protected} access, 573 * which may contribute to the result of {@link #lookupModes lookupModes}. 574 * The value, {@code 0x04}, happens to be the same as the value of the 575 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 576 */ 577 public static final int PROTECTED = Modifier.PROTECTED; 578 579 /** A single-bit mask representing {@code package} access (default access), 580 * which may contribute to the result of {@link #lookupModes lookupModes}. 581 * The value is {@code 0x08}, which does not correspond meaningfully to 582 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 583 */ 584 public static final int PACKAGE = Modifier.STATIC; 585 586 /** A single-bit mask representing {@code module} access (default access), 587 * which may contribute to the result of {@link #lookupModes lookupModes}. 588 * The value is {@code 0x10}, which does not correspond meaningfully to 589 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 590 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 591 * with this lookup mode can access all public types in the module of the 592 * lookup class and public types in packages exported by other modules 593 * to the module of the lookup class. 594 * @since 9 595 */ 596 public static final int MODULE = PACKAGE << 1; 597 598 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE); 599 private static final int TRUSTED = -1; 600 601 private static int fixmods(int mods) { 602 mods &= (ALL_MODES - PACKAGE - MODULE); 603 return (mods != 0) ? mods : (PACKAGE | MODULE); 604 } 605 606 /** Tells which class is performing the lookup. It is this class against 607 * which checks are performed for visibility and access permissions. 608 * <p> 609 * The class implies a maximum level of access permission, 610 * but the permissions may be additionally limited by the bitmask 611 * {@link #lookupModes lookupModes}, which controls whether non-public members 612 * can be accessed. 613 * @return the lookup class, on behalf of which this lookup object finds members 614 */ 615 public Class<?> lookupClass() { 616 return lookupClass; 617 } 618 619 // This is just for calling out to MethodHandleImpl. 620 private Class<?> lookupClassOrNull() { 621 return (allowedModes == TRUSTED) ? null : lookupClass; 622 } 623 624 /** Tells which access-protection classes of members this lookup object can produce. 625 * The result is a bit-mask of the bits 626 * {@linkplain #PUBLIC PUBLIC (0x01)}, 627 * {@linkplain #PRIVATE PRIVATE (0x02)}, 628 * {@linkplain #PROTECTED PROTECTED (0x04)}, 629 * {@linkplain #PACKAGE PACKAGE (0x08)}, 630 * and {@linkplain #MODULE MODULE (0x10)}. 631 * <p> 632 * A freshly-created lookup object 633 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} 634 * has all possible bits set, since the caller class can access all its own members, 635 * all public types in the caller's module, and all public types in packages exported 636 * by other modules to the caller's module. 637 * A lookup object on a new lookup class 638 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 639 * may have some mode bits set to zero. 640 * The purpose of this is to restrict access via the new lookup object, 641 * so that it can access only names which can be reached by the original 642 * lookup object, and also by the new lookup class. 643 * @return the lookup modes, which limit the kinds of access performed by this lookup object 644 */ 645 public int lookupModes() { 646 return allowedModes & ALL_MODES; 647 } 648 649 /** Embody the current class (the lookupClass) as a lookup class 650 * for method handle creation. 651 * Must be called by from a method in this package, 652 * which in turn is called by a method not in this package. 653 */ 654 Lookup(Class<?> lookupClass) { 655 this(lookupClass, ALL_MODES); 656 // make sure we haven't accidentally picked up a privileged class: 657 checkUnprivilegedlookupClass(lookupClass, ALL_MODES); 658 } 659 660 private Lookup(Class<?> lookupClass, int allowedModes) { 661 this.lookupClass = lookupClass; 662 this.allowedModes = allowedModes; 663 } 664 665 /** 666 * Creates a lookup on the specified new lookup class. 667 * The resulting object will report the specified 668 * class as its own {@link #lookupClass lookupClass}. 669 * <p> 670 * However, the resulting {@code Lookup} object is guaranteed 671 * to have no more access capabilities than the original. 672 * In particular, access capabilities can be lost as follows:<ul> 673 * <li>If the lookup class for this {@code Lookup} is not in a named module, 674 * and the new lookup class is in a named module {@code M}, then no members in 675 * {@code M}'s non-exported packages will be accessible. 676 * <li>If the lookup for this {@code Lookup} is in a named module, and the 677 * new lookup class is in a different module {@code M}, then no members, not even 678 * public members in {@code M}'s exported packages, will be accessible. 679 * <li>If the new lookup class differs from the old one, 680 * protected members will not be accessible by virtue of inheritance. 681 * (Protected members may continue to be accessible because of package sharing.) 682 * <li>If the new lookup class is in a different package 683 * than the old one, protected and default (package) members will not be accessible. 684 * <li>If the new lookup class is not within the same package member 685 * as the old one, private members will not be accessible. 686 * <li>If the new lookup class is not accessible to the old lookup class, 687 * then no members, not even public members, will be accessible. 688 * (In all other cases, public members will continue to be accessible.) 689 * </ul> 690 * <p> 691 * The resulting lookup's capabilities for loading classes 692 * (used during {@link #findClass} invocations) 693 * are determined by the lookup class' loader, 694 * which may change due to this operation. 695 * 696 * @param requestedLookupClass the desired lookup class for the new lookup object 697 * @return a lookup object which reports the desired lookup class 698 * @throws NullPointerException if the argument is null 699 */ 700 public Lookup in(Class<?> requestedLookupClass) { 701 Objects.requireNonNull(requestedLookupClass); 702 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 703 return new Lookup(requestedLookupClass, ALL_MODES); 704 if (requestedLookupClass == this.lookupClass) 705 return this; // keep same capabilities 706 707 int newModes = (allowedModes & (ALL_MODES & ~PROTECTED)); 708 if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) { 709 // Allowed to teleport from an unnamed to a named module but resulting 710 // Lookup has no access to module private members 711 if (this.lookupClass.getModule().isNamed()) { 712 newModes = 0; 713 } else { 714 newModes &= ~MODULE; 715 } 716 } 717 if ((newModes & PACKAGE) != 0 718 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 719 newModes &= ~(PACKAGE|PRIVATE); 720 } 721 // Allow nestmate lookups to be created without special privilege: 722 if ((newModes & PRIVATE) != 0 723 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 724 newModes &= ~PRIVATE; 725 } 726 if ((newModes & PUBLIC) != 0 727 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) { 728 // The requested class it not accessible from the lookup class. 729 // No permissions. 730 newModes = 0; 731 } 732 733 checkUnprivilegedlookupClass(requestedLookupClass, newModes); 734 return new Lookup(requestedLookupClass, newModes); 735 } 736 737 // Make sure outer class is initialized first. 738 static { IMPL_NAMES.getClass(); } 739 740 /** Package-private version of lookup which is trusted. */ 741 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED); 742 743 private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) { 744 String name = lookupClass.getName(); 745 if (name.startsWith("java.lang.invoke.")) 746 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 747 748 // For caller-sensitive MethodHandles.lookup() disallow lookup from 749 // restricted packages. This a fragile and blunt approach. 750 // TODO replace with a more formal and less fragile mechanism 751 // that does not bluntly restrict classes under packages within 752 // java.base from looking up MethodHandles or VarHandles. 753 if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) { 754 if ((name.startsWith("java.") && !name.startsWith("java.util.concurrent.")) || 755 (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) { 756 throw newIllegalArgumentException("illegal lookupClass: " + lookupClass); 757 } 758 } 759 } 760 761 /** 762 * Displays the name of the class from which lookups are to be made. 763 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 764 * If there are restrictions on the access permitted to this lookup, 765 * this is indicated by adding a suffix to the class name, consisting 766 * of a slash and a keyword. The keyword represents the strongest 767 * allowed access, and is chosen as follows: 768 * <ul> 769 * <li>If no access is allowed, the suffix is "/noaccess". 770 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 771 * <li>If only public and module access are allowed, the suffix is "/module". 772 * <li>If only public, module and package access are allowed, the suffix is "/package". 773 * <li>If only public, module, package, and private access are allowed, the suffix is "/private". 774 * </ul> 775 * If none of the above cases apply, it is the case that full 776 * access (public, module, package, private, and protected) is allowed. 777 * In this case, no suffix is added. 778 * This is true only of an object obtained originally from 779 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 780 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 781 * always have restricted access, and will display a suffix. 782 * <p> 783 * (It may seem strange that protected access should be 784 * stronger than private access. Viewed independently from 785 * package access, protected access is the first to be lost, 786 * because it requires a direct subclass relationship between 787 * caller and callee.) 788 * @see #in 789 */ 790 @Override 791 public String toString() { 792 String cname = lookupClass.getName(); 793 switch (allowedModes) { 794 case 0: // no privileges 795 return cname + "/noaccess"; 796 case PUBLIC: 797 return cname + "/public"; 798 case PUBLIC|MODULE: 799 return cname + "/module"; 800 case PUBLIC|MODULE|PACKAGE: 801 return cname + "/package"; 802 case ALL_MODES & ~PROTECTED: 803 return cname + "/private"; 804 case ALL_MODES: 805 return cname; 806 case TRUSTED: 807 return "/trusted"; // internal only; not exported 808 default: // Should not happen, but it's a bitfield... 809 cname = cname + "/" + Integer.toHexString(allowedModes); 810 assert(false) : cname; 811 return cname; 812 } 813 } 814 815 /** 816 * Produces a method handle for a static method. 817 * The type of the method handle will be that of the method. 818 * (Since static methods do not take receivers, there is no 819 * additional receiver argument inserted into the method handle type, 820 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 821 * The method and all its argument types must be accessible to the lookup object. 822 * <p> 823 * The returned method handle will have 824 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 825 * the method's variable arity modifier bit ({@code 0x0080}) is set. 826 * <p> 827 * If the returned method handle is invoked, the method's class will 828 * be initialized, if it has not already been initialized. 829 * <p><b>Example:</b> 830 * <blockquote><pre>{@code 831 import static java.lang.invoke.MethodHandles.*; 832 import static java.lang.invoke.MethodType.*; 833 ... 834 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 835 "asList", methodType(List.class, Object[].class)); 836 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 837 * }</pre></blockquote> 838 * @param refc the class from which the method is accessed 839 * @param name the name of the method 840 * @param type the type of the method 841 * @return the desired method handle 842 * @throws NoSuchMethodException if the method does not exist 843 * @throws IllegalAccessException if access checking fails, 844 * or if the method is not {@code static}, 845 * or if the method's variable arity modifier bit 846 * is set and {@code asVarargsCollector} fails 847 * @exception SecurityException if a security manager is present and it 848 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 849 * @throws NullPointerException if any argument is null 850 */ 851 public 852 MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 853 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 854 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method)); 855 } 856 857 /** 858 * Produces a method handle for a virtual method. 859 * The type of the method handle will be that of the method, 860 * with the receiver type (usually {@code refc}) prepended. 861 * The method and all its argument types must be accessible to the lookup object. 862 * <p> 863 * When called, the handle will treat the first argument as a receiver 864 * and dispatch on the receiver's type to determine which method 865 * implementation to enter. 866 * (The dispatching action is identical with that performed by an 867 * {@code invokevirtual} or {@code invokeinterface} instruction.) 868 * <p> 869 * The first argument will be of type {@code refc} if the lookup 870 * class has full privileges to access the member. Otherwise 871 * the member must be {@code protected} and the first argument 872 * will be restricted in type to the lookup class. 873 * <p> 874 * The returned method handle will have 875 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 876 * the method's variable arity modifier bit ({@code 0x0080}) is set. 877 * <p> 878 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 879 * instructions and method handles produced by {@code findVirtual}, 880 * if the class is {@code MethodHandle} and the name string is 881 * {@code invokeExact} or {@code invoke}, the resulting 882 * method handle is equivalent to one produced by 883 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 884 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 885 * with the same {@code type} argument. 886 * <p> 887 * If the class is {@code VarHandle} and the name string corresponds to 888 * the name of a signature-polymorphic access mode method, the resulting 889 * method handle is equivalent to one produced by 890 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 891 * the access mode corresponding to the name string and with the same 892 * {@code type} arguments. 893 * <p> 894 * <b>Example:</b> 895 * <blockquote><pre>{@code 896 import static java.lang.invoke.MethodHandles.*; 897 import static java.lang.invoke.MethodType.*; 898 ... 899 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 900 "concat", methodType(String.class, String.class)); 901 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 902 "hashCode", methodType(int.class)); 903 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 904 "hashCode", methodType(int.class)); 905 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 906 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 907 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 908 // interface method: 909 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 910 "subSequence", methodType(CharSequence.class, int.class, int.class)); 911 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 912 // constructor "internal method" must be accessed differently: 913 MethodType MT_newString = methodType(void.class); //()V for new String() 914 try { assertEquals("impossible", lookup() 915 .findVirtual(String.class, "<init>", MT_newString)); 916 } catch (NoSuchMethodException ex) { } // OK 917 MethodHandle MH_newString = publicLookup() 918 .findConstructor(String.class, MT_newString); 919 assertEquals("", (String) MH_newString.invokeExact()); 920 * }</pre></blockquote> 921 * 922 * @param refc the class or interface from which the method is accessed 923 * @param name the name of the method 924 * @param type the type of the method, with the receiver argument omitted 925 * @return the desired method handle 926 * @throws NoSuchMethodException if the method does not exist 927 * @throws IllegalAccessException if access checking fails, 928 * or if the method is {@code static}, 929 * or if the method is {@code private} method of interface, 930 * or if the method's variable arity modifier bit 931 * is set and {@code asVarargsCollector} fails 932 * @exception SecurityException if a security manager is present and it 933 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 934 * @throws NullPointerException if any argument is null 935 */ 936 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 937 if (refc == MethodHandle.class) { 938 MethodHandle mh = findVirtualForMH(name, type); 939 if (mh != null) return mh; 940 } else if (refc == VarHandle.class) { 941 MethodHandle mh = findVirtualForVH(name, type); 942 if (mh != null) return mh; 943 } 944 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 945 MemberName method = resolveOrFail(refKind, refc, name, type); 946 return getDirectMethod(refKind, refc, method, findBoundCallerClass(method)); 947 } 948 private MethodHandle findVirtualForMH(String name, MethodType type) { 949 // these names require special lookups because of the implicit MethodType argument 950 if ("invoke".equals(name)) 951 return invoker(type); 952 if ("invokeExact".equals(name)) 953 return exactInvoker(type); 954 if ("invokeBasic".equals(name)) 955 return basicInvoker(type); 956 assert(!MemberName.isMethodHandleInvokeName(name)); 957 return null; 958 } 959 private MethodHandle findVirtualForVH(String name, MethodType type) { 960 try { 961 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 962 } catch (IllegalArgumentException e) { 963 return null; 964 } 965 } 966 967 /** 968 * Produces a method handle which creates an object and initializes it, using 969 * the constructor of the specified type. 970 * The parameter types of the method handle will be those of the constructor, 971 * while the return type will be a reference to the constructor's class. 972 * The constructor and all its argument types must be accessible to the lookup object. 973 * <p> 974 * The requested type must have a return type of {@code void}. 975 * (This is consistent with the JVM's treatment of constructor type descriptors.) 976 * <p> 977 * The returned method handle will have 978 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 979 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 980 * <p> 981 * If the returned method handle is invoked, the constructor's class will 982 * be initialized, if it has not already been initialized. 983 * <p><b>Example:</b> 984 * <blockquote><pre>{@code 985 import static java.lang.invoke.MethodHandles.*; 986 import static java.lang.invoke.MethodType.*; 987 ... 988 MethodHandle MH_newArrayList = publicLookup().findConstructor( 989 ArrayList.class, methodType(void.class, Collection.class)); 990 Collection orig = Arrays.asList("x", "y"); 991 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 992 assert(orig != copy); 993 assertEquals(orig, copy); 994 // a variable-arity constructor: 995 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 996 ProcessBuilder.class, methodType(void.class, String[].class)); 997 ProcessBuilder pb = (ProcessBuilder) 998 MH_newProcessBuilder.invoke("x", "y", "z"); 999 assertEquals("[x, y, z]", pb.command().toString()); 1000 * }</pre></blockquote> 1001 * @param refc the class or interface from which the method is accessed 1002 * @param type the type of the method, with the receiver argument omitted, and a void return type 1003 * @return the desired method handle 1004 * @throws NoSuchMethodException if the constructor does not exist 1005 * @throws IllegalAccessException if access checking fails 1006 * or if the method's variable arity modifier bit 1007 * is set and {@code asVarargsCollector} fails 1008 * @exception SecurityException if a security manager is present and it 1009 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1010 * @throws NullPointerException if any argument is null 1011 */ 1012 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1013 if (refc.isArray()) { 1014 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 1015 } 1016 String name = "<init>"; 1017 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 1018 return getDirectConstructor(refc, ctor); 1019 } 1020 1021 /** 1022 * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static 1023 * initializer of the class is not run. 1024 * <p> 1025 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class 1026 * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to 1027 * load the requested class, and then determines whether the class is accessible to this lookup object. 1028 * 1029 * @param targetName the fully qualified name of the class to be looked up. 1030 * @return the requested class. 1031 * @exception SecurityException if a security manager is present and it 1032 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1033 * @throws LinkageError if the linkage fails 1034 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 1035 * @throws IllegalAccessException if the class is not accessible, using the allowed access 1036 * modes. 1037 * @exception SecurityException if a security manager is present and it 1038 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1039 * @since 9 1040 */ 1041 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 1042 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 1043 return accessClass(targetClass); 1044 } 1045 1046 /** 1047 * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The 1048 * static initializer of the class is not run. 1049 * <p> 1050 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the 1051 * {@linkplain #lookupModes() lookup modes}. 1052 * 1053 * @param targetClass the class to be access-checked 1054 * 1055 * @return the class that has been access-checked 1056 * 1057 * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access 1058 * modes. 1059 * @exception SecurityException if a security manager is present and it 1060 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1061 * @since 9 1062 */ 1063 public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException { 1064 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) { 1065 throw new MemberName(targetClass).makeAccessException("access violation", this); 1066 } 1067 checkSecurityManager(targetClass, null); 1068 return targetClass; 1069 } 1070 1071 /** 1072 * Produces an early-bound method handle for a virtual method. 1073 * It will bypass checks for overriding methods on the receiver, 1074 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1075 * instruction from within the explicitly specified {@code specialCaller}. 1076 * The type of the method handle will be that of the method, 1077 * with a suitably restricted receiver type prepended. 1078 * (The receiver type will be {@code specialCaller} or a subtype.) 1079 * The method and all its argument types must be accessible 1080 * to the lookup object. 1081 * <p> 1082 * Before method resolution, 1083 * if the explicitly specified caller class is not identical with the 1084 * lookup class, or if this lookup object does not have 1085 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1086 * privileges, the access fails. 1087 * <p> 1088 * The returned method handle will have 1089 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1090 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1091 * <p style="font-size:smaller;"> 1092 * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API, 1093 * even though the {@code invokespecial} instruction can refer to them 1094 * in special circumstances. Use {@link #findConstructor findConstructor} 1095 * to access instance initialization methods in a safe manner.)</em> 1096 * <p><b>Example:</b> 1097 * <blockquote><pre>{@code 1098 import static java.lang.invoke.MethodHandles.*; 1099 import static java.lang.invoke.MethodType.*; 1100 ... 1101 static class Listie extends ArrayList { 1102 public String toString() { return "[wee Listie]"; } 1103 static Lookup lookup() { return MethodHandles.lookup(); } 1104 } 1105 ... 1106 // no access to constructor via invokeSpecial: 1107 MethodHandle MH_newListie = Listie.lookup() 1108 .findConstructor(Listie.class, methodType(void.class)); 1109 Listie l = (Listie) MH_newListie.invokeExact(); 1110 try { assertEquals("impossible", Listie.lookup().findSpecial( 1111 Listie.class, "<init>", methodType(void.class), Listie.class)); 1112 } catch (NoSuchMethodException ex) { } // OK 1113 // access to super and self methods via invokeSpecial: 1114 MethodHandle MH_super = Listie.lookup().findSpecial( 1115 ArrayList.class, "toString" , methodType(String.class), Listie.class); 1116 MethodHandle MH_this = Listie.lookup().findSpecial( 1117 Listie.class, "toString" , methodType(String.class), Listie.class); 1118 MethodHandle MH_duper = Listie.lookup().findSpecial( 1119 Object.class, "toString" , methodType(String.class), Listie.class); 1120 assertEquals("[]", (String) MH_super.invokeExact(l)); 1121 assertEquals(""+l, (String) MH_this.invokeExact(l)); 1122 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 1123 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 1124 String.class, "toString", methodType(String.class), Listie.class)); 1125 } catch (IllegalAccessException ex) { } // OK 1126 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 1127 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 1128 * }</pre></blockquote> 1129 * 1130 * @param refc the class or interface from which the method is accessed 1131 * @param name the name of the method (which must not be "<init>") 1132 * @param type the type of the method, with the receiver argument omitted 1133 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 1134 * @return the desired method handle 1135 * @throws NoSuchMethodException if the method does not exist 1136 * @throws IllegalAccessException if access checking fails, 1137 * or if the method is {@code static}, 1138 * or if the method's variable arity modifier bit 1139 * is set and {@code asVarargsCollector} fails 1140 * @exception SecurityException if a security manager is present and it 1141 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1142 * @throws NullPointerException if any argument is null 1143 */ 1144 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 1145 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 1146 checkSpecialCaller(specialCaller, refc); 1147 Lookup specialLookup = this.in(specialCaller); 1148 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 1149 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); 1150 } 1151 1152 /** 1153 * Produces a method handle giving read access to a non-static field. 1154 * The type of the method handle will have a return type of the field's 1155 * value type. 1156 * The method handle's single argument will be the instance containing 1157 * the field. 1158 * Access checking is performed immediately on behalf of the lookup class. 1159 * @param refc the class or interface from which the method is accessed 1160 * @param name the field's name 1161 * @param type the field's type 1162 * @return a method handle which can load values from the field 1163 * @throws NoSuchFieldException if the field does not exist 1164 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1165 * @exception SecurityException if a security manager is present and it 1166 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1167 * @throws NullPointerException if any argument is null 1168 * @see #findVarHandle(Class, String, Class) 1169 */ 1170 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1171 MemberName field = resolveOrFail(REF_getField, refc, name, type); 1172 return getDirectField(REF_getField, refc, field); 1173 } 1174 1175 /** 1176 * Produces a method handle giving write access to a non-static field. 1177 * The type of the method handle will have a void return type. 1178 * The method handle will take two arguments, the instance containing 1179 * the field, and the value to be stored. 1180 * The second argument will be of the field's value type. 1181 * Access checking is performed immediately on behalf of the lookup class. 1182 * @param refc the class or interface from which the method is accessed 1183 * @param name the field's name 1184 * @param type the field's type 1185 * @return a method handle which can store values into the field 1186 * @throws NoSuchFieldException if the field does not exist 1187 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1188 * @exception SecurityException if a security manager is present and it 1189 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1190 * @throws NullPointerException if any argument is null 1191 * @see #findVarHandle(Class, String, Class) 1192 */ 1193 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1194 MemberName field = resolveOrFail(REF_putField, refc, name, type); 1195 return getDirectField(REF_putField, refc, field); 1196 } 1197 1198 /** 1199 * Produces a VarHandle giving access to non-static fields of type 1200 * {@code T} declared by a receiver class of type {@code R}, supporting 1201 * shape {@code (R : T)}. 1202 * <p> 1203 * Access checking is performed immediately on behalf of the lookup 1204 * class. 1205 * <p> 1206 * Certain access modes of the returned VarHandle are unsupported under 1207 * the following conditions: 1208 * <ul> 1209 * <li>if the field is declared {@code final}, then the write, atomic 1210 * update, and numeric atomic update access modes are unsupported. 1211 * <li>if the field type is anything other than {@code byte}, 1212 * {@code short}, {@code char}, {@code int} or {@code long}, 1213 * {@code float}, or {@code double} then numeric atomic update 1214 * access modes are unsupported. 1215 * </ul> 1216 * <p> 1217 * If the field is declared {@code volatile} then the returned VarHandle 1218 * will override access to the field (effectively ignore the 1219 * {@code volatile} declaration) in accordance to it's specified 1220 * access modes. 1221 * <p> 1222 * If the field type is {@code float} or {@code double} then numeric 1223 * and atomic update access modes compare values using their bitwise 1224 * representation (see {@link Float#floatToRawIntBits} and 1225 * {@link Double#doubleToRawLongBits}, respectively). 1226 * @apiNote 1227 * Bitwise comparison of {@code float} values or {@code double} values, 1228 * as performed by the numeric and atomic update access modes, differ 1229 * from the primitive {@code ==} operator and the {@link Float#equals} 1230 * and {@link Double#equals} methods, specifically with respect to 1231 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1232 * Care should be taken when performing a compare and set or a compare 1233 * and exchange operation with such values since the operation may 1234 * unexpectedly fail. 1235 * There are many possible NaN values that are considered to be 1236 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1237 * provided by Java can distinguish between them. Operation failure can 1238 * occur if the expected or witness value is a NaN value and it is 1239 * transformed (perhaps in a platform specific manner) into another NaN 1240 * value, and thus has a different bitwise representation (see 1241 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1242 * details). 1243 * The values {@code -0.0} and {@code +0.0} have different bitwise 1244 * representations but are considered equal when using the primitive 1245 * {@code ==} operator. Operation failure can occur if, for example, a 1246 * numeric algorithm computes an expected value to be say {@code -0.0} 1247 * and previously computed the witness value to be say {@code +0.0}. 1248 * @param recv the receiver class, of type {@code R}, that declares the 1249 * non-static field 1250 * @param name the field's name 1251 * @param type the field's type, of type {@code T} 1252 * @return a VarHandle giving access to non-static fields. 1253 * @throws NoSuchFieldException if the field does not exist 1254 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1255 * @exception SecurityException if a security manager is present and it 1256 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1257 * @throws NullPointerException if any argument is null 1258 * @since 9 1259 */ 1260 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1261 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 1262 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 1263 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 1264 } 1265 1266 /** 1267 * Produces a method handle giving read access to a static field. 1268 * The type of the method handle will have a return type of the field's 1269 * value type. 1270 * The method handle will take no arguments. 1271 * Access checking is performed immediately on behalf of the lookup class. 1272 * <p> 1273 * If the returned method handle is invoked, the field's class will 1274 * be initialized, if it has not already been initialized. 1275 * @param refc the class or interface from which the method is accessed 1276 * @param name the field's name 1277 * @param type the field's type 1278 * @return a method handle which can load values from the field 1279 * @throws NoSuchFieldException if the field does not exist 1280 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1281 * @exception SecurityException if a security manager is present and it 1282 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1283 * @throws NullPointerException if any argument is null 1284 */ 1285 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1286 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 1287 return getDirectField(REF_getStatic, refc, field); 1288 } 1289 1290 /** 1291 * Produces a method handle giving write access to a static field. 1292 * The type of the method handle will have a void return type. 1293 * The method handle will take a single 1294 * argument, of the field's value type, the value to be stored. 1295 * Access checking is performed immediately on behalf of the lookup class. 1296 * <p> 1297 * If the returned method handle is invoked, the field's class will 1298 * be initialized, if it has not already been initialized. 1299 * @param refc the class or interface from which the method is accessed 1300 * @param name the field's name 1301 * @param type the field's type 1302 * @return a method handle which can store values into the field 1303 * @throws NoSuchFieldException if the field does not exist 1304 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1305 * @exception SecurityException if a security manager is present and it 1306 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1307 * @throws NullPointerException if any argument is null 1308 */ 1309 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1310 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 1311 return getDirectField(REF_putStatic, refc, field); 1312 } 1313 1314 /** 1315 * Produces a VarHandle giving access to a static field of type 1316 * {@code T} declared by a given declaring class, supporting shape 1317 * {@code ((empty) : T)}. 1318 * <p> 1319 * Access checking is performed immediately on behalf of the lookup 1320 * class. 1321 * <p> 1322 * If the returned VarHandle is operated on, the declaring class will be 1323 * initialized, if it has not already been initialized. 1324 * <p> 1325 * Certain access modes of the returned VarHandle are unsupported under 1326 * the following conditions: 1327 * <ul> 1328 * <li>if the field is declared {@code final}, then the write, atomic 1329 * update, and numeric atomic update access modes are unsupported. 1330 * <li>if the field type is anything other than {@code byte}, 1331 * {@code short}, {@code char}, {@code int} or {@code long}, 1332 * {@code float}, or {@code double}, then numeric atomic update 1333 * access modes are unsupported. 1334 * </ul> 1335 * <p> 1336 * If the field is declared {@code volatile} then the returned VarHandle 1337 * will override access to the field (effectively ignore the 1338 * {@code volatile} declaration) in accordance to it's specified 1339 * access modes. 1340 * <p> 1341 * If the field type is {@code float} or {@code double} then numeric 1342 * and atomic update access modes compare values using their bitwise 1343 * representation (see {@link Float#floatToRawIntBits} and 1344 * {@link Double#doubleToRawLongBits}, respectively). 1345 * @apiNote 1346 * Bitwise comparison of {@code float} values or {@code double} values, 1347 * as performed by the numeric and atomic update access modes, differ 1348 * from the primitive {@code ==} operator and the {@link Float#equals} 1349 * and {@link Double#equals} methods, specifically with respect to 1350 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1351 * Care should be taken when performing a compare and set or a compare 1352 * and exchange operation with such values since the operation may 1353 * unexpectedly fail. 1354 * There are many possible NaN values that are considered to be 1355 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1356 * provided by Java can distinguish between them. Operation failure can 1357 * occur if the expected or witness value is a NaN value and it is 1358 * transformed (perhaps in a platform specific manner) into another NaN 1359 * value, and thus has a different bitwise representation (see 1360 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1361 * details). 1362 * The values {@code -0.0} and {@code +0.0} have different bitwise 1363 * representations but are considered equal when using the primitive 1364 * {@code ==} operator. Operation failure can occur if, for example, a 1365 * numeric algorithm computes an expected value to be say {@code -0.0} 1366 * and previously computed the witness value to be say {@code +0.0}. 1367 * @param decl the class that declares the static field 1368 * @param name the field's name 1369 * @param type the field's type, of type {@code T} 1370 * @return a VarHandle giving access to a static field 1371 * @throws NoSuchFieldException if the field does not exist 1372 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1373 * @exception SecurityException if a security manager is present and it 1374 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1375 * @throws NullPointerException if any argument is null 1376 * @since 9 1377 */ 1378 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1379 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 1380 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 1381 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 1382 } 1383 1384 /** 1385 * Produces an early-bound method handle for a non-static method. 1386 * The receiver must have a supertype {@code defc} in which a method 1387 * of the given name and type is accessible to the lookup class. 1388 * The method and all its argument types must be accessible to the lookup object. 1389 * The type of the method handle will be that of the method, 1390 * without any insertion of an additional receiver parameter. 1391 * The given receiver will be bound into the method handle, 1392 * so that every call to the method handle will invoke the 1393 * requested method on the given receiver. 1394 * <p> 1395 * The returned method handle will have 1396 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1397 * the method's variable arity modifier bit ({@code 0x0080}) is set 1398 * <em>and</em> the trailing array argument is not the only argument. 1399 * (If the trailing array argument is the only argument, 1400 * the given receiver value will be bound to it.) 1401 * <p> 1402 * This is equivalent to the following code: 1403 * <blockquote><pre>{@code 1404 import static java.lang.invoke.MethodHandles.*; 1405 import static java.lang.invoke.MethodType.*; 1406 ... 1407 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 1408 MethodHandle mh1 = mh0.bindTo(receiver); 1409 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 1410 return mh1; 1411 * }</pre></blockquote> 1412 * where {@code defc} is either {@code receiver.getClass()} or a super 1413 * type of that class, in which the requested method is accessible 1414 * to the lookup class. 1415 * (Note that {@code bindTo} does not preserve variable arity.) 1416 * @param receiver the object from which the method is accessed 1417 * @param name the name of the method 1418 * @param type the type of the method, with the receiver argument omitted 1419 * @return the desired method handle 1420 * @throws NoSuchMethodException if the method does not exist 1421 * @throws IllegalAccessException if access checking fails 1422 * or if the method's variable arity modifier bit 1423 * is set and {@code asVarargsCollector} fails 1424 * @exception SecurityException if a security manager is present and it 1425 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1426 * @throws NullPointerException if any argument is null 1427 * @see MethodHandle#bindTo 1428 * @see #findVirtual 1429 */ 1430 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1431 Class<? extends Object> refc = receiver.getClass(); // may get NPE 1432 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 1433 MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); 1434 return mh.bindArgumentL(0, receiver).setVarargs(method); 1435 } 1436 1437 /** 1438 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1439 * to <i>m</i>, if the lookup class has permission. 1440 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 1441 * If <i>m</i> is virtual, overriding is respected on every call. 1442 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 1443 * The type of the method handle will be that of the method, 1444 * with the receiver type prepended (but only if it is non-static). 1445 * If the method's {@code accessible} flag is not set, 1446 * access checking is performed immediately on behalf of the lookup class. 1447 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 1448 * <p> 1449 * The returned method handle will have 1450 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1451 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1452 * <p> 1453 * If <i>m</i> is static, and 1454 * if the returned method handle is invoked, the method's class will 1455 * be initialized, if it has not already been initialized. 1456 * @param m the reflected method 1457 * @return a method handle which can invoke the reflected method 1458 * @throws IllegalAccessException if access checking fails 1459 * or if the method's variable arity modifier bit 1460 * is set and {@code asVarargsCollector} fails 1461 * @throws NullPointerException if the argument is null 1462 */ 1463 public MethodHandle unreflect(Method m) throws IllegalAccessException { 1464 if (m.getDeclaringClass() == MethodHandle.class) { 1465 MethodHandle mh = unreflectForMH(m); 1466 if (mh != null) return mh; 1467 } 1468 if (m.getDeclaringClass() == VarHandle.class) { 1469 MethodHandle mh = unreflectForVH(m); 1470 if (mh != null) return mh; 1471 } 1472 MemberName method = new MemberName(m); 1473 byte refKind = method.getReferenceKind(); 1474 if (refKind == REF_invokeSpecial) 1475 refKind = REF_invokeVirtual; 1476 assert(method.isMethod()); 1477 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 1478 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1479 } 1480 private MethodHandle unreflectForMH(Method m) { 1481 // these names require special lookups because they throw UnsupportedOperationException 1482 if (MemberName.isMethodHandleInvokeName(m.getName())) 1483 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 1484 return null; 1485 } 1486 private MethodHandle unreflectForVH(Method m) { 1487 // these names require special lookups because they throw UnsupportedOperationException 1488 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 1489 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 1490 return null; 1491 } 1492 1493 /** 1494 * Produces a method handle for a reflected method. 1495 * It will bypass checks for overriding methods on the receiver, 1496 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1497 * instruction from within the explicitly specified {@code specialCaller}. 1498 * The type of the method handle will be that of the method, 1499 * with a suitably restricted receiver type prepended. 1500 * (The receiver type will be {@code specialCaller} or a subtype.) 1501 * If the method's {@code accessible} flag is not set, 1502 * access checking is performed immediately on behalf of the lookup class, 1503 * as if {@code invokespecial} instruction were being linked. 1504 * <p> 1505 * Before method resolution, 1506 * if the explicitly specified caller class is not identical with the 1507 * lookup class, or if this lookup object does not have 1508 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1509 * privileges, the access fails. 1510 * <p> 1511 * The returned method handle will have 1512 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1513 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1514 * @param m the reflected method 1515 * @param specialCaller the class nominally calling the method 1516 * @return a method handle which can invoke the reflected method 1517 * @throws IllegalAccessException if access checking fails, 1518 * or if the method is {@code static}, 1519 * or if the method's variable arity modifier bit 1520 * is set and {@code asVarargsCollector} fails 1521 * @throws NullPointerException if any argument is null 1522 */ 1523 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 1524 checkSpecialCaller(specialCaller, null); 1525 Lookup specialLookup = this.in(specialCaller); 1526 MemberName method = new MemberName(m, true); 1527 assert(method.isMethod()); 1528 // ignore m.isAccessible: this is a new kind of access 1529 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1530 } 1531 1532 /** 1533 * Produces a method handle for a reflected constructor. 1534 * The type of the method handle will be that of the constructor, 1535 * with the return type changed to the declaring class. 1536 * The method handle will perform a {@code newInstance} operation, 1537 * creating a new instance of the constructor's class on the 1538 * arguments passed to the method handle. 1539 * <p> 1540 * If the constructor's {@code accessible} flag is not set, 1541 * access checking is performed immediately on behalf of the lookup class. 1542 * <p> 1543 * The returned method handle will have 1544 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1545 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 1546 * <p> 1547 * If the returned method handle is invoked, the constructor's class will 1548 * be initialized, if it has not already been initialized. 1549 * @param c the reflected constructor 1550 * @return a method handle which can invoke the reflected constructor 1551 * @throws IllegalAccessException if access checking fails 1552 * or if the method's variable arity modifier bit 1553 * is set and {@code asVarargsCollector} fails 1554 * @throws NullPointerException if the argument is null 1555 */ 1556 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 1557 MemberName ctor = new MemberName(c); 1558 assert(ctor.isConstructor()); 1559 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 1560 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 1561 } 1562 1563 /** 1564 * Produces a method handle giving read access to a reflected field. 1565 * The type of the method handle will have a return type of the field's 1566 * value type. 1567 * If the field is static, the method handle will take no arguments. 1568 * Otherwise, its single argument will be the instance containing 1569 * the field. 1570 * If the field's {@code accessible} flag is not set, 1571 * access checking is performed immediately on behalf of the lookup class. 1572 * <p> 1573 * If the field is static, and 1574 * if the returned method handle is invoked, the field's class will 1575 * be initialized, if it has not already been initialized. 1576 * @param f the reflected field 1577 * @return a method handle which can load values from the reflected field 1578 * @throws IllegalAccessException if access checking fails 1579 * @throws NullPointerException if the argument is null 1580 */ 1581 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 1582 return unreflectField(f, false); 1583 } 1584 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 1585 MemberName field = new MemberName(f, isSetter); 1586 assert(isSetter 1587 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 1588 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 1589 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 1590 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 1591 } 1592 1593 /** 1594 * Produces a method handle giving write access to a reflected field. 1595 * The type of the method handle will have a void return type. 1596 * If the field is static, the method handle will take a single 1597 * argument, of the field's value type, the value to be stored. 1598 * Otherwise, the two arguments will be the instance containing 1599 * the field, and the value to be stored. 1600 * If the field's {@code accessible} flag is not set, 1601 * access checking is performed immediately on behalf of the lookup class. 1602 * <p> 1603 * If the field is static, and 1604 * if the returned method handle is invoked, the field's class will 1605 * be initialized, if it has not already been initialized. 1606 * @param f the reflected field 1607 * @return a method handle which can store values into the reflected field 1608 * @throws IllegalAccessException if access checking fails 1609 * @throws NullPointerException if the argument is null 1610 */ 1611 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 1612 return unreflectField(f, true); 1613 } 1614 1615 /** 1616 * Produces a VarHandle that accesses fields of type {@code T} declared 1617 * by a class of type {@code R}, as described by the given reflected 1618 * field. 1619 * If the field is non-static the VarHandle supports a shape of 1620 * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}. 1621 * <p> 1622 * Access checking is performed immediately on behalf of the lookup 1623 * class, regardless of the value of the field's {@code accessible} 1624 * flag. 1625 * <p> 1626 * If the field is static, and if the returned VarHandle is operated 1627 * on, the field's declaring class will be initialized, if it has not 1628 * already been initialized. 1629 * <p> 1630 * Certain access modes of the returned VarHandle are unsupported under 1631 * the following conditions: 1632 * <ul> 1633 * <li>if the field is declared {@code final}, then the write, atomic 1634 * update, and numeric atomic update access modes are unsupported. 1635 * <li>if the field type is anything other than {@code byte}, 1636 * {@code short}, {@code char}, {@code int} or {@code long}, 1637 * {@code float}, or {@code double} then numeric atomic update 1638 * access modes are unsupported. 1639 * </ul> 1640 * <p> 1641 * If the field is declared {@code volatile} then the returned VarHandle 1642 * will override access to the field (effectively ignore the 1643 * {@code volatile} declaration) in accordance to it's specified 1644 * access modes. 1645 * <p> 1646 * If the field type is {@code float} or {@code double} then numeric 1647 * and atomic update access modes compare values using their bitwise 1648 * representation (see {@link Float#floatToRawIntBits} and 1649 * {@link Double#doubleToRawLongBits}, respectively). 1650 * @apiNote 1651 * Bitwise comparison of {@code float} values or {@code double} values, 1652 * as performed by the numeric and atomic update access modes, differ 1653 * from the primitive {@code ==} operator and the {@link Float#equals} 1654 * and {@link Double#equals} methods, specifically with respect to 1655 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1656 * Care should be taken when performing a compare and set or a compare 1657 * and exchange operation with such values since the operation may 1658 * unexpectedly fail. 1659 * There are many possible NaN values that are considered to be 1660 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1661 * provided by Java can distinguish between them. Operation failure can 1662 * occur if the expected or witness value is a NaN value and it is 1663 * transformed (perhaps in a platform specific manner) into another NaN 1664 * value, and thus has a different bitwise representation (see 1665 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1666 * details). 1667 * The values {@code -0.0} and {@code +0.0} have different bitwise 1668 * representations but are considered equal when using the primitive 1669 * {@code ==} operator. Operation failure can occur if, for example, a 1670 * numeric algorithm computes an expected value to be say {@code -0.0} 1671 * and previously computed the witness value to be say {@code +0.0}. 1672 * @param f the reflected field, with a field of type {@code T}, and 1673 * a declaring class of type {@code R} 1674 * @return a VarHandle giving access to non-static fields or a static 1675 * field 1676 * @throws IllegalAccessException if access checking fails 1677 * @throws NullPointerException if the argument is null 1678 * @since 9 1679 */ 1680 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 1681 MemberName getField = new MemberName(f, false); 1682 MemberName putField = new MemberName(f, true); 1683 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 1684 f.getDeclaringClass(), getField, putField); 1685 } 1686 1687 /** 1688 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1689 * created by this lookup object or a similar one. 1690 * Security and access checks are performed to ensure that this lookup object 1691 * is capable of reproducing the target method handle. 1692 * This means that the cracking may fail if target is a direct method handle 1693 * but was created by an unrelated lookup object. 1694 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 1695 * and was created by a lookup object for a different class. 1696 * @param target a direct method handle to crack into symbolic reference components 1697 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 1698 * @exception SecurityException if a security manager is present and it 1699 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1700 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 1701 * @exception NullPointerException if the target is {@code null} 1702 * @see MethodHandleInfo 1703 * @since 1.8 1704 */ 1705 public MethodHandleInfo revealDirect(MethodHandle target) { 1706 MemberName member = target.internalMemberName(); 1707 if (member == null || (!member.isResolved() && 1708 !member.isMethodHandleInvoke() && 1709 !member.isVarHandleMethodInvoke())) 1710 throw newIllegalArgumentException("not a direct method handle"); 1711 Class<?> defc = member.getDeclaringClass(); 1712 byte refKind = member.getReferenceKind(); 1713 assert(MethodHandleNatives.refKindIsValid(refKind)); 1714 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 1715 // Devirtualized method invocation is usually formally virtual. 1716 // To avoid creating extra MemberName objects for this common case, 1717 // we encode this extra degree of freedom using MH.isInvokeSpecial. 1718 refKind = REF_invokeVirtual; 1719 if (refKind == REF_invokeVirtual && defc.isInterface()) 1720 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 1721 refKind = REF_invokeInterface; 1722 // Check SM permissions and member access before cracking. 1723 try { 1724 checkAccess(refKind, defc, member); 1725 checkSecurityManager(defc, member); 1726 } catch (IllegalAccessException ex) { 1727 throw new IllegalArgumentException(ex); 1728 } 1729 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 1730 Class<?> callerClass = target.internalCallerClass(); 1731 if (!hasPrivateAccess() || callerClass != lookupClass()) 1732 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 1733 } 1734 // Produce the handle to the results. 1735 return new InfoFromMemberName(this, member, refKind); 1736 } 1737 1738 /// Helper methods, all package-private. 1739 1740 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1741 checkSymbolicClass(refc); // do this before attempting to resolve 1742 Objects.requireNonNull(name); 1743 Objects.requireNonNull(type); 1744 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1745 NoSuchFieldException.class); 1746 } 1747 1748 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1749 checkSymbolicClass(refc); // do this before attempting to resolve 1750 Objects.requireNonNull(name); 1751 Objects.requireNonNull(type); 1752 checkMethodName(refKind, name); // NPE check on name 1753 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1754 NoSuchMethodException.class); 1755 } 1756 1757 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 1758 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 1759 Objects.requireNonNull(member.getName()); 1760 Objects.requireNonNull(member.getType()); 1761 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), 1762 ReflectiveOperationException.class); 1763 } 1764 1765 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 1766 Objects.requireNonNull(refc); 1767 Class<?> caller = lookupClassOrNull(); 1768 if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes)) 1769 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 1770 } 1771 1772 /** Check name for an illegal leading "<" character. */ 1773 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 1774 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 1775 throw new NoSuchMethodException("illegal method name: "+name); 1776 } 1777 1778 1779 /** 1780 * Find my trustable caller class if m is a caller sensitive method. 1781 * If this lookup object has private access, then the caller class is the lookupClass. 1782 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 1783 */ 1784 Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException { 1785 Class<?> callerClass = null; 1786 if (MethodHandleNatives.isCallerSensitive(m)) { 1787 // Only lookups with private access are allowed to resolve caller-sensitive methods 1788 if (hasPrivateAccess()) { 1789 callerClass = lookupClass; 1790 } else { 1791 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 1792 } 1793 } 1794 return callerClass; 1795 } 1796 1797 private boolean hasPrivateAccess() { 1798 return (allowedModes & PRIVATE) != 0; 1799 } 1800 1801 /** 1802 * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 1803 * Determines a trustable caller class to compare with refc, the symbolic reference class. 1804 * If this lookup object has private access, then the caller class is the lookupClass. 1805 */ 1806 void checkSecurityManager(Class<?> refc, MemberName m) { 1807 SecurityManager smgr = System.getSecurityManager(); 1808 if (smgr == null) return; 1809 if (allowedModes == TRUSTED) return; 1810 1811 // Step 1: 1812 boolean fullPowerLookup = hasPrivateAccess(); 1813 if (!fullPowerLookup || 1814 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 1815 ReflectUtil.checkPackageAccess(refc); 1816 } 1817 1818 if (m == null) { // findClass or accessClass 1819 // Step 2b: 1820 if (!fullPowerLookup) { 1821 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 1822 } 1823 return; 1824 } 1825 1826 // Step 2a: 1827 if (m.isPublic()) return; 1828 if (!fullPowerLookup) { 1829 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 1830 } 1831 1832 // Step 3: 1833 Class<?> defc = m.getDeclaringClass(); 1834 if (!fullPowerLookup && defc != refc) { 1835 ReflectUtil.checkPackageAccess(defc); 1836 } 1837 } 1838 1839 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1840 boolean wantStatic = (refKind == REF_invokeStatic); 1841 String message; 1842 if (m.isConstructor()) 1843 message = "expected a method, not a constructor"; 1844 else if (!m.isMethod()) 1845 message = "expected a method"; 1846 else if (wantStatic != m.isStatic()) 1847 message = wantStatic ? "expected a static method" : "expected a non-static method"; 1848 else 1849 { checkAccess(refKind, refc, m); return; } 1850 throw m.makeAccessException(message, this); 1851 } 1852 1853 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1854 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 1855 String message; 1856 if (wantStatic != m.isStatic()) 1857 message = wantStatic ? "expected a static field" : "expected a non-static field"; 1858 else 1859 { checkAccess(refKind, refc, m); return; } 1860 throw m.makeAccessException(message, this); 1861 } 1862 1863 /** Check public/protected/private bits on the symbolic reference class and its member. */ 1864 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1865 assert(m.referenceKindIsConsistentWith(refKind) && 1866 MethodHandleNatives.refKindIsValid(refKind) && 1867 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 1868 int allowedModes = this.allowedModes; 1869 if (allowedModes == TRUSTED) return; 1870 int mods = m.getModifiers(); 1871 if (Modifier.isProtected(mods) && 1872 refKind == REF_invokeVirtual && 1873 m.getDeclaringClass() == Object.class && 1874 m.getName().equals("clone") && 1875 refc.isArray()) { 1876 // The JVM does this hack also. 1877 // (See ClassVerifier::verify_invoke_instructions 1878 // and LinkResolver::check_method_accessability.) 1879 // Because the JVM does not allow separate methods on array types, 1880 // there is no separate method for int[].clone. 1881 // All arrays simply inherit Object.clone. 1882 // But for access checking logic, we make Object.clone 1883 // (normally protected) appear to be public. 1884 // Later on, when the DirectMethodHandle is created, 1885 // its leading argument will be restricted to the 1886 // requested array type. 1887 // N.B. The return type is not adjusted, because 1888 // that is *not* the bytecode behavior. 1889 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 1890 } 1891 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 1892 // cannot "new" a protected ctor in a different package 1893 mods ^= Modifier.PROTECTED; 1894 } 1895 if (Modifier.isFinal(mods) && 1896 MethodHandleNatives.refKindIsSetter(refKind)) 1897 throw m.makeAccessException("unexpected set of a final field", this); 1898 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 1899 if ((requestedModes & allowedModes) != 0) { 1900 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 1901 mods, lookupClass(), allowedModes)) 1902 return; 1903 } else { 1904 // Protected members can also be checked as if they were package-private. 1905 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 1906 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 1907 return; 1908 } 1909 throw m.makeAccessException(accessFailedMessage(refc, m), this); 1910 } 1911 1912 String accessFailedMessage(Class<?> refc, MemberName m) { 1913 Class<?> defc = m.getDeclaringClass(); 1914 int mods = m.getModifiers(); 1915 // check the class first: 1916 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 1917 (defc == refc || 1918 Modifier.isPublic(refc.getModifiers()))); 1919 if (!classOK && (allowedModes & PACKAGE) != 0) { 1920 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) && 1921 (defc == refc || 1922 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES))); 1923 } 1924 if (!classOK) 1925 return "class is not public"; 1926 if (Modifier.isPublic(mods)) 1927 return "access to public member failed"; // (how?, module not readable?) 1928 if (Modifier.isPrivate(mods)) 1929 return "member is private"; 1930 if (Modifier.isProtected(mods)) 1931 return "member is protected"; 1932 return "member is private to package"; 1933 } 1934 1935 private static final boolean ALLOW_NESTMATE_ACCESS = false; 1936 1937 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 1938 int allowedModes = this.allowedModes; 1939 if (allowedModes == TRUSTED) return; 1940 if (!hasPrivateAccess() 1941 || (specialCaller != lookupClass() 1942 // ensure non-abstract methods in superinterfaces can be special-invoked 1943 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)) 1944 && !(ALLOW_NESTMATE_ACCESS && 1945 VerifyAccess.isSamePackageMember(specialCaller, lookupClass())))) 1946 throw new MemberName(specialCaller). 1947 makeAccessException("no private access for invokespecial", this); 1948 } 1949 1950 private boolean restrictProtectedReceiver(MemberName method) { 1951 // The accessing class only has the right to use a protected member 1952 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 1953 if (!method.isProtected() || method.isStatic() 1954 || allowedModes == TRUSTED 1955 || method.getDeclaringClass() == lookupClass() 1956 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()) 1957 || (ALLOW_NESTMATE_ACCESS && 1958 VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass()))) 1959 return false; 1960 return true; 1961 } 1962 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 1963 assert(!method.isStatic()); 1964 // receiver type of mh is too wide; narrow to caller 1965 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 1966 throw method.makeAccessException("caller class must be a subclass below the method", caller); 1967 } 1968 MethodType rawType = mh.type(); 1969 if (rawType.parameterType(0) == caller) return mh; 1970 MethodType narrowType = rawType.changeParameterType(0, caller); 1971 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 1972 assert(mh.viewAsTypeChecks(narrowType, true)); 1973 return mh.copyWith(narrowType, mh.form); 1974 } 1975 1976 /** Check access and get the requested method. */ 1977 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1978 final boolean doRestrict = true; 1979 final boolean checkSecurity = true; 1980 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1981 } 1982 /** Check access and get the requested method, eliding receiver narrowing rules. */ 1983 private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1984 final boolean doRestrict = false; 1985 final boolean checkSecurity = true; 1986 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1987 } 1988 /** Check access and get the requested method, eliding security manager checks. */ 1989 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1990 final boolean doRestrict = true; 1991 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 1992 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1993 } 1994 /** Common code for all methods; do not call directly except from immediately above. */ 1995 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 1996 boolean checkSecurity, 1997 boolean doRestrict, Class<?> callerClass) throws IllegalAccessException { 1998 checkMethod(refKind, refc, method); 1999 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2000 if (checkSecurity) 2001 checkSecurityManager(refc, method); 2002 assert(!method.isMethodHandleInvoke()); 2003 2004 if (refKind == REF_invokeSpecial && 2005 refc != lookupClass() && 2006 !refc.isInterface() && 2007 refc != lookupClass().getSuperclass() && 2008 refc.isAssignableFrom(lookupClass())) { 2009 assert(!method.getName().equals("<init>")); // not this code path 2010 // Per JVMS 6.5, desc. of invokespecial instruction: 2011 // If the method is in a superclass of the LC, 2012 // and if our original search was above LC.super, 2013 // repeat the search (symbolic lookup) from LC.super 2014 // and continue with the direct superclass of that class, 2015 // and so forth, until a match is found or no further superclasses exist. 2016 // FIXME: MemberName.resolve should handle this instead. 2017 Class<?> refcAsSuper = lookupClass(); 2018 MemberName m2; 2019 do { 2020 refcAsSuper = refcAsSuper.getSuperclass(); 2021 m2 = new MemberName(refcAsSuper, 2022 method.getName(), 2023 method.getMethodType(), 2024 REF_invokeSpecial); 2025 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); 2026 } while (m2 == null && // no method is found yet 2027 refc != refcAsSuper); // search up to refc 2028 if (m2 == null) throw new InternalError(method.toString()); 2029 method = m2; 2030 refc = refcAsSuper; 2031 // redo basic checks 2032 checkMethod(refKind, refc, method); 2033 } 2034 2035 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method); 2036 MethodHandle mh = dmh; 2037 // Optionally narrow the receiver argument to refc using restrictReceiver. 2038 if (doRestrict && 2039 (refKind == REF_invokeSpecial || 2040 (MethodHandleNatives.refKindHasReceiver(refKind) && 2041 restrictProtectedReceiver(method)))) { 2042 mh = restrictReceiver(method, dmh, lookupClass()); 2043 } 2044 mh = maybeBindCaller(method, mh, callerClass); 2045 mh = mh.setVarargs(method); 2046 return mh; 2047 } 2048 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, 2049 Class<?> callerClass) 2050 throws IllegalAccessException { 2051 if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 2052 return mh; 2053 Class<?> hostClass = lookupClass; 2054 if (!hasPrivateAccess()) // caller must have private access 2055 hostClass = callerClass; // callerClass came from a security manager style stack walk 2056 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); 2057 // Note: caller will apply varargs after this step happens. 2058 return cbmh; 2059 } 2060 /** Check access and get the requested field. */ 2061 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 2062 final boolean checkSecurity = true; 2063 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2064 } 2065 /** Check access and get the requested field, eliding security manager checks. */ 2066 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 2067 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2068 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2069 } 2070 /** Common code for all fields; do not call directly except from immediately above. */ 2071 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 2072 boolean checkSecurity) throws IllegalAccessException { 2073 checkField(refKind, refc, field); 2074 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2075 if (checkSecurity) 2076 checkSecurityManager(refc, field); 2077 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 2078 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 2079 restrictProtectedReceiver(field)); 2080 if (doRestrict) 2081 return restrictReceiver(field, dmh, lookupClass()); 2082 return dmh; 2083 } 2084 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 2085 Class<?> refc, MemberName getField, MemberName putField) 2086 throws IllegalAccessException { 2087 final boolean checkSecurity = true; 2088 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2089 } 2090 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 2091 Class<?> refc, MemberName getField, MemberName putField) 2092 throws IllegalAccessException { 2093 final boolean checkSecurity = false; 2094 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2095 } 2096 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 2097 Class<?> refc, MemberName getField, MemberName putField, 2098 boolean checkSecurity) throws IllegalAccessException { 2099 assert getField.isStatic() == putField.isStatic(); 2100 assert getField.isGetter() && putField.isSetter(); 2101 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 2102 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 2103 2104 checkField(getRefKind, refc, getField); 2105 if (checkSecurity) 2106 checkSecurityManager(refc, getField); 2107 2108 if (!putField.isFinal()) { 2109 // A VarHandle does not support updates to final fields, any 2110 // such VarHandle to a final field will be read-only and 2111 // therefore the following write-based accessibility checks are 2112 // only required for non-final fields 2113 checkField(putRefKind, refc, putField); 2114 if (checkSecurity) 2115 checkSecurityManager(refc, putField); 2116 } 2117 2118 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 2119 restrictProtectedReceiver(getField)); 2120 if (doRestrict) { 2121 assert !getField.isStatic(); 2122 // receiver type of VarHandle is too wide; narrow to caller 2123 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 2124 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 2125 } 2126 refc = lookupClass(); 2127 } 2128 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED); 2129 } 2130 /** Check access and get the requested constructor. */ 2131 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2132 final boolean checkSecurity = true; 2133 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2134 } 2135 /** Check access and get the requested constructor, eliding security manager checks. */ 2136 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2137 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2138 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2139 } 2140 /** Common code for all constructors; do not call directly except from immediately above. */ 2141 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 2142 boolean checkSecurity) throws IllegalAccessException { 2143 assert(ctor.isConstructor()); 2144 checkAccess(REF_newInvokeSpecial, refc, ctor); 2145 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2146 if (checkSecurity) 2147 checkSecurityManager(refc, ctor); 2148 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 2149 return DirectMethodHandle.make(ctor).setVarargs(ctor); 2150 } 2151 2152 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 2153 */ 2154 /*non-public*/ 2155 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { 2156 if (!(type instanceof Class || type instanceof MethodType)) 2157 throw new InternalError("unresolved MemberName"); 2158 MemberName member = new MemberName(refKind, defc, name, type); 2159 MethodHandle mh = LOOKASIDE_TABLE.get(member); 2160 if (mh != null) { 2161 checkSymbolicClass(defc); 2162 return mh; 2163 } 2164 // Treat MethodHandle.invoke and invokeExact specially. 2165 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 2166 mh = findVirtualForMH(member.getName(), member.getMethodType()); 2167 if (mh != null) { 2168 return mh; 2169 } 2170 } 2171 MemberName resolved = resolveOrFail(refKind, member); 2172 mh = getDirectMethodForConstant(refKind, defc, resolved); 2173 if (mh instanceof DirectMethodHandle 2174 && canBeCached(refKind, defc, resolved)) { 2175 MemberName key = mh.internalMemberName(); 2176 if (key != null) { 2177 key = key.asNormalOriginal(); 2178 } 2179 if (member.equals(key)) { // better safe than sorry 2180 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 2181 } 2182 } 2183 return mh; 2184 } 2185 private 2186 boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 2187 if (refKind == REF_invokeSpecial) { 2188 return false; 2189 } 2190 if (!Modifier.isPublic(defc.getModifiers()) || 2191 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 2192 !member.isPublic() || 2193 member.isCallerSensitive()) { 2194 return false; 2195 } 2196 ClassLoader loader = defc.getClassLoader(); 2197 if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) { 2198 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 2199 boolean found = false; 2200 while (sysl != null) { 2201 if (loader == sysl) { found = true; break; } 2202 sysl = sysl.getParent(); 2203 } 2204 if (!found) { 2205 return false; 2206 } 2207 } 2208 try { 2209 MemberName resolved2 = publicLookup().resolveOrFail(refKind, 2210 new MemberName(refKind, defc, member.getName(), member.getType())); 2211 checkSecurityManager(defc, resolved2); 2212 } catch (ReflectiveOperationException | SecurityException ex) { 2213 return false; 2214 } 2215 return true; 2216 } 2217 private 2218 MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 2219 throws ReflectiveOperationException { 2220 if (MethodHandleNatives.refKindIsField(refKind)) { 2221 return getDirectFieldNoSecurityManager(refKind, defc, member); 2222 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 2223 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); 2224 } else if (refKind == REF_newInvokeSpecial) { 2225 return getDirectConstructorNoSecurityManager(defc, member); 2226 } 2227 // oops 2228 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 2229 } 2230 2231 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 2232 } 2233 2234 /** 2235 * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class 2236 * in an <em>unnamed module</em>. 2237 * 2238 * @see Lookup#publicLookup 2239 */ 2240 private static class LookupHelper { 2241 private static final String UNNAMED = "Unnamed"; 2242 private static final String OBJECT = "java/lang/Object"; 2243 2244 private static Class<?> createClass() { 2245 try { 2246 ClassWriter cw = new ClassWriter(0); 2247 cw.visit(Opcodes.V1_8, 2248 Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, 2249 UNNAMED, 2250 null, 2251 OBJECT, 2252 null); 2253 cw.visitSource(UNNAMED, null); 2254 cw.visitEnd(); 2255 byte[] bytes = cw.toByteArray(); 2256 ClassLoader loader = new ClassLoader(null) { 2257 @Override 2258 protected Class<?> findClass(String cn) throws ClassNotFoundException { 2259 if (cn.equals(UNNAMED)) 2260 return super.defineClass(UNNAMED, bytes, 0, bytes.length); 2261 throw new ClassNotFoundException(cn); 2262 } 2263 }; 2264 return loader.loadClass(UNNAMED); 2265 } catch (Exception e) { 2266 throw new InternalError(e); 2267 } 2268 } 2269 2270 private static final Class<?> PUBLIC_LOOKUP_CLASS = createClass(); 2271 2272 /** 2273 * Lookup that is trusted minimally. It can only be used to create 2274 * method handles to publicly accessible members in exported packages. 2275 * 2276 * @see MethodHandles#publicLookup 2277 */ 2278 static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC); 2279 } 2280 2281 /** 2282 * Produces a method handle constructing arrays of a desired type. 2283 * The return type of the method handle will be the array type. 2284 * The type of its sole argument will be {@code int}, which specifies the size of the array. 2285 * @param arrayClass an array type 2286 * @return a method handle which can create arrays of the given type 2287 * @throws NullPointerException if the argument is {@code null} 2288 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 2289 * @see java.lang.reflect.Array#newInstance(Class, int) 2290 * @since 9 2291 */ 2292 public static 2293 MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 2294 if (!arrayClass.isArray()) { 2295 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 2296 } 2297 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 2298 bindTo(arrayClass.getComponentType()); 2299 return ani.asType(ani.type().changeReturnType(arrayClass)); 2300 } 2301 2302 /** 2303 * Produces a method handle returning the length of an array. 2304 * The type of the method handle will have {@code int} as return type, 2305 * and its sole argument will be the array type. 2306 * @param arrayClass an array type 2307 * @return a method handle which can retrieve the length of an array of the given array type 2308 * @throws NullPointerException if the argument is {@code null} 2309 * @throws IllegalArgumentException if arrayClass is not an array type 2310 * @since 9 2311 */ 2312 public static 2313 MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 2314 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 2315 } 2316 2317 /** 2318 * Produces a method handle giving read access to elements of an array. 2319 * The type of the method handle will have a return type of the array's 2320 * element type. Its first argument will be the array type, 2321 * and the second will be {@code int}. 2322 * @param arrayClass an array type 2323 * @return a method handle which can load values from the given array type 2324 * @throws NullPointerException if the argument is null 2325 * @throws IllegalArgumentException if arrayClass is not an array type 2326 */ 2327 public static 2328 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 2329 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 2330 } 2331 2332 /** 2333 * Produces a method handle giving write access to elements of an array. 2334 * The type of the method handle will have a void return type. 2335 * Its last argument will be the array's element type. 2336 * The first and second arguments will be the array type and int. 2337 * @param arrayClass the class of an array 2338 * @return a method handle which can store values into the array type 2339 * @throws NullPointerException if the argument is null 2340 * @throws IllegalArgumentException if arrayClass is not an array type 2341 */ 2342 public static 2343 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 2344 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 2345 } 2346 2347 /** 2348 * 2349 * Produces a VarHandle giving access to elements of an array type 2350 * {@code T[]}, supporting shape {@code (T[], int : T)}. 2351 * <p> 2352 * Certain access modes of the returned VarHandle are unsupported under 2353 * the following conditions: 2354 * <ul> 2355 * <li>if the component type is anything other than {@code byte}, 2356 * {@code short}, {@code char}, {@code int} or {@code long}, 2357 * {@code float}, or {@code double} then numeric atomic update access 2358 * modes are unsupported. 2359 * </ul> 2360 * <p> 2361 * If the component type is {@code float} or {@code double} then numeric 2362 * and atomic update access modes compare values using their bitwise 2363 * representation (see {@link Float#floatToRawIntBits} and 2364 * {@link Double#doubleToRawLongBits}, respectively). 2365 * @apiNote 2366 * Bitwise comparison of {@code float} values or {@code double} values, 2367 * as performed by the numeric and atomic update access modes, differ 2368 * from the primitive {@code ==} operator and the {@link Float#equals} 2369 * and {@link Double#equals} methods, specifically with respect to 2370 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 2371 * Care should be taken when performing a compare and set or a compare 2372 * and exchange operation with such values since the operation may 2373 * unexpectedly fail. 2374 * There are many possible NaN values that are considered to be 2375 * {@code NaN} in Java, although no IEEE 754 floating-point operation 2376 * provided by Java can distinguish between them. Operation failure can 2377 * occur if the expected or witness value is a NaN value and it is 2378 * transformed (perhaps in a platform specific manner) into another NaN 2379 * value, and thus has a different bitwise representation (see 2380 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 2381 * details). 2382 * The values {@code -0.0} and {@code +0.0} have different bitwise 2383 * representations but are considered equal when using the primitive 2384 * {@code ==} operator. Operation failure can occur if, for example, a 2385 * numeric algorithm computes an expected value to be say {@code -0.0} 2386 * and previously computed the witness value to be say {@code +0.0}. 2387 * @param arrayClass the class of an array, of type {@code T[]} 2388 * @return a VarHandle giving access to elements of an array 2389 * @throws NullPointerException if the arrayClass is null 2390 * @throws IllegalArgumentException if arrayClass is not an array type 2391 * @since 9 2392 */ 2393 public static 2394 VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 2395 return VarHandles.makeArrayElementHandle(arrayClass); 2396 } 2397 2398 /** 2399 * Produces a VarHandle giving access to elements of a {@code byte[]} array 2400 * viewed as if it were a different primitive array type, such as 2401 * {@code int[]} or {@code long[]}. The shape of the resulting VarHandle is 2402 * {@code (byte[], int : T)}, where the {@code int} coordinate type 2403 * corresponds to an argument that is an index in a {@code byte[]} array, 2404 * and {@code T} is the component type of the given view array class. The 2405 * returned VarHandle accesses bytes at an index in a {@code byte[]} array, 2406 * composing bytes to or from a value of {@code T} according to the given 2407 * endianness. 2408 * <p> 2409 * The supported component types (variables types) are {@code short}, 2410 * {@code char}, {@code int}, {@code long}, {@code float} and 2411 * {@code double}. 2412 * <p> 2413 * Access of bytes at a given index will result in an 2414 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2415 * or greater than the {@code byte[]} array length minus the size (in bytes) 2416 * of {@code T}. 2417 * <p> 2418 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2419 * with respect to the underlying memory address, {@code A} say, associated 2420 * with the array and index. 2421 * If access is misaligned then access for anything other than the 2422 * {@code get} and {@code set} access modes will result in an 2423 * {@code IllegalStateException}. In such cases atomic access is only 2424 * guaranteed with respect to the largest power of two that divides the GCD 2425 * of {@code A} and the size (in bytes) of {@code T}. 2426 * If access is aligned then following access modes are supported and are 2427 * guaranteed to support atomic access: 2428 * <ul> 2429 * <li>read write access modes for all {@code T}; 2430 * <li>atomic update access modes for {@code int}, {@code long}, 2431 * {@code float} or {@code double}. 2432 * (Future major platform releases of the JDK may support additional 2433 * types for certain currently unsupported access modes.) 2434 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2435 * (Future major platform releases of the JDK may support additional 2436 * numeric types for certain currently unsupported access modes.) 2437 * </ul> 2438 * <p> 2439 * Misaligned access, and therefore atomicity guarantees, may be determined 2440 * for {@code byte[]} arrays without operating on a specific array. Given 2441 * an {@code index}, {@code T} and it's corresponding boxed type, 2442 * {@code T_BOX}, misalignment may be determined as follows: 2443 * <pre>{@code 2444 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2445 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 2446 * alignmentOffset(0, sizeOfT); 2447 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 2448 * boolean isMisaligned = misalignedAtIndex != 0; 2449 * }</pre> 2450 * <p> 2451 * If the variable type is {@code float} or {@code double} then atomic 2452 * update access modes compare values using their bitwise representation 2453 * (see {@link Float#floatToRawIntBits} and 2454 * {@link Double#doubleToRawLongBits}, respectively). 2455 * @param viewArrayClass the view array class, with a component type of 2456 * type {@code T} 2457 * @param byteOrder the endianness of the view array elements, as 2458 * stored in the underlying {@code byte} array 2459 * @return a VarHandle giving access to elements of a {@code byte[]} array 2460 * viewed as if elements corresponding to the components type of the view 2461 * array class 2462 * @throws NullPointerException if viewArrayClass or byteOrder is null 2463 * @throws IllegalArgumentException if viewArrayClass is not an array type 2464 * @throws UnsupportedOperationException if the component type of 2465 * viewArrayClass is not supported as a variable type 2466 * @since 9 2467 */ 2468 public static 2469 VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 2470 ByteOrder byteOrder) throws IllegalArgumentException { 2471 Objects.requireNonNull(byteOrder); 2472 return VarHandles.byteArrayViewHandle(viewArrayClass, 2473 byteOrder == ByteOrder.BIG_ENDIAN); 2474 } 2475 2476 /** 2477 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 2478 * viewed as if it were an array of elements of a different primitive 2479 * component type to that of {@code byte}, such as {@code int[]} or 2480 * {@code long[]}. The shape of the resulting VarHandle is 2481 * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type 2482 * corresponds to an argument that is an index in a {@code ByteBuffer}, and 2483 * {@code T} is the component type of the given view array class. The 2484 * returned VarHandle accesses bytes at an index in a {@code ByteBuffer}, 2485 * composing bytes to or from a value of {@code T} according to the given 2486 * endianness. 2487 * <p> 2488 * The supported component types (variables types) are {@code short}, 2489 * {@code char}, {@code int}, {@code long}, {@code float} and 2490 * {@code double}. 2491 * <p> 2492 * Access will result in a {@code ReadOnlyBufferException} for anything 2493 * other than the read access modes if the {@code ByteBuffer} is read-only. 2494 * <p> 2495 * Access of bytes at a given index will result in an 2496 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2497 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 2498 * {@code T}. 2499 * <p> 2500 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2501 * with respect to the underlying memory address, {@code A} say, associated 2502 * with the {@code ByteBuffer} and index. 2503 * If access is misaligned then access for anything other than the 2504 * {@code get} and {@code set} access modes will result in an 2505 * {@code IllegalStateException}. In such cases atomic access is only 2506 * guaranteed with respect to the largest power of two that divides the GCD 2507 * of {@code A} and the size (in bytes) of {@code T}. 2508 * If access is aligned then following access modes are supported and are 2509 * guaranteed to support atomic access: 2510 * <ul> 2511 * <li>read write access modes for all {@code T}; 2512 * <li>atomic update access modes for {@code int}, {@code long}, 2513 * {@code float} or {@code double}. 2514 * (Future major platform releases of the JDK may support additional 2515 * types for certain currently unsupported access modes.) 2516 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2517 * (Future major platform releases of the JDK may support additional 2518 * numeric types for certain currently unsupported access modes.) 2519 * </ul> 2520 * <p> 2521 * Misaligned access, and therefore atomicity guarantees, may be determined 2522 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 2523 * {@code index}, {@code T} and it's corresponding boxed type, 2524 * {@code T_BOX}, as follows: 2525 * <pre>{@code 2526 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2527 * ByteBuffer bb = ... 2528 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 2529 * boolean isMisaligned = misalignedAtIndex != 0; 2530 * }</pre> 2531 * <p> 2532 * If the variable type is {@code float} or {@code double} then atomic 2533 * update access modes compare values using their bitwise representation 2534 * (see {@link Float#floatToRawIntBits} and 2535 * {@link Double#doubleToRawLongBits}, respectively). 2536 * @param viewArrayClass the view array class, with a component type of 2537 * type {@code T} 2538 * @param byteOrder the endianness of the view array elements, as 2539 * stored in the underlying {@code ByteBuffer} (Note this overrides the 2540 * endianness of a {@code ByteBuffer}) 2541 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 2542 * viewed as if elements corresponding to the components type of the view 2543 * array class 2544 * @throws NullPointerException if viewArrayClass or byteOrder is null 2545 * @throws IllegalArgumentException if viewArrayClass is not an array type 2546 * @throws UnsupportedOperationException if the component type of 2547 * viewArrayClass is not supported as a variable type 2548 * @since 9 2549 */ 2550 public static 2551 VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 2552 ByteOrder byteOrder) throws IllegalArgumentException { 2553 Objects.requireNonNull(byteOrder); 2554 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 2555 byteOrder == ByteOrder.BIG_ENDIAN); 2556 } 2557 2558 2559 /// method handle invocation (reflective style) 2560 2561 /** 2562 * Produces a method handle which will invoke any method handle of the 2563 * given {@code type}, with a given number of trailing arguments replaced by 2564 * a single trailing {@code Object[]} array. 2565 * The resulting invoker will be a method handle with the following 2566 * arguments: 2567 * <ul> 2568 * <li>a single {@code MethodHandle} target 2569 * <li>zero or more leading values (counted by {@code leadingArgCount}) 2570 * <li>an {@code Object[]} array containing trailing arguments 2571 * </ul> 2572 * <p> 2573 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 2574 * the indicated {@code type}. 2575 * That is, if the target is exactly of the given {@code type}, it will behave 2576 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 2577 * is used to convert the target to the required {@code type}. 2578 * <p> 2579 * The type of the returned invoker will not be the given {@code type}, but rather 2580 * will have all parameters except the first {@code leadingArgCount} 2581 * replaced by a single array of type {@code Object[]}, which will be 2582 * the final parameter. 2583 * <p> 2584 * Before invoking its target, the invoker will spread the final array, apply 2585 * reference casts as necessary, and unbox and widen primitive arguments. 2586 * If, when the invoker is called, the supplied array argument does 2587 * not have the correct number of elements, the invoker will throw 2588 * an {@link IllegalArgumentException} instead of invoking the target. 2589 * <p> 2590 * This method is equivalent to the following code (though it may be more efficient): 2591 * <blockquote><pre>{@code 2592 MethodHandle invoker = MethodHandles.invoker(type); 2593 int spreadArgCount = type.parameterCount() - leadingArgCount; 2594 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 2595 return invoker; 2596 * }</pre></blockquote> 2597 * This method throws no reflective or security exceptions. 2598 * @param type the desired target type 2599 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 2600 * @return a method handle suitable for invoking any method handle of the given type 2601 * @throws NullPointerException if {@code type} is null 2602 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 2603 * the range from 0 to {@code type.parameterCount()} inclusive, 2604 * or if the resulting method handle's type would have 2605 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2606 */ 2607 public static 2608 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 2609 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 2610 throw newIllegalArgumentException("bad argument count", leadingArgCount); 2611 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 2612 return type.invokers().spreadInvoker(leadingArgCount); 2613 } 2614 2615 /** 2616 * Produces a special <em>invoker method handle</em> which can be used to 2617 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 2618 * The resulting invoker will have a type which is 2619 * exactly equal to the desired type, except that it will accept 2620 * an additional leading argument of type {@code MethodHandle}. 2621 * <p> 2622 * This method is equivalent to the following code (though it may be more efficient): 2623 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 2624 * 2625 * <p style="font-size:smaller;"> 2626 * <em>Discussion:</em> 2627 * Invoker method handles can be useful when working with variable method handles 2628 * of unknown types. 2629 * For example, to emulate an {@code invokeExact} call to a variable method 2630 * handle {@code M}, extract its type {@code T}, 2631 * look up the invoker method {@code X} for {@code T}, 2632 * and call the invoker method, as {@code X.invoke(T, A...)}. 2633 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 2634 * is unknown.) 2635 * If spreading, collecting, or other argument transformations are required, 2636 * they can be applied once to the invoker {@code X} and reused on many {@code M} 2637 * method handle values, as long as they are compatible with the type of {@code X}. 2638 * <p style="font-size:smaller;"> 2639 * <em>(Note: The invoker method is not available via the Core Reflection API. 2640 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2641 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2642 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2643 * <p> 2644 * This method throws no reflective or security exceptions. 2645 * @param type the desired target type 2646 * @return a method handle suitable for invoking any method handle of the given type 2647 * @throws IllegalArgumentException if the resulting method handle's type would have 2648 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2649 */ 2650 public static 2651 MethodHandle exactInvoker(MethodType type) { 2652 return type.invokers().exactInvoker(); 2653 } 2654 2655 /** 2656 * Produces a special <em>invoker method handle</em> which can be used to 2657 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 2658 * The resulting invoker will have a type which is 2659 * exactly equal to the desired type, except that it will accept 2660 * an additional leading argument of type {@code MethodHandle}. 2661 * <p> 2662 * Before invoking its target, if the target differs from the expected type, 2663 * the invoker will apply reference casts as 2664 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 2665 * Similarly, the return value will be converted as necessary. 2666 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 2667 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 2668 * <p> 2669 * This method is equivalent to the following code (though it may be more efficient): 2670 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 2671 * <p style="font-size:smaller;"> 2672 * <em>Discussion:</em> 2673 * A {@linkplain MethodType#genericMethodType general method type} is one which 2674 * mentions only {@code Object} arguments and return values. 2675 * An invoker for such a type is capable of calling any method handle 2676 * of the same arity as the general type. 2677 * <p style="font-size:smaller;"> 2678 * <em>(Note: The invoker method is not available via the Core Reflection API. 2679 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2680 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2681 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2682 * <p> 2683 * This method throws no reflective or security exceptions. 2684 * @param type the desired target type 2685 * @return a method handle suitable for invoking any method handle convertible to the given type 2686 * @throws IllegalArgumentException if the resulting method handle's type would have 2687 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2688 */ 2689 public static 2690 MethodHandle invoker(MethodType type) { 2691 return type.invokers().genericInvoker(); 2692 } 2693 2694 /** 2695 * Produces a special <em>invoker method handle</em> which can be used to 2696 * invoke a signature-polymorphic access mode method on any VarHandle whose 2697 * associated access mode type is compatible with the given type. 2698 * The resulting invoker will have a type which is exactly equal to the 2699 * desired given type, except that it will accept an additional leading 2700 * argument of type {@code VarHandle}. 2701 * 2702 * @param accessMode the VarHandle access mode 2703 * @param type the desired target type 2704 * @return a method handle suitable for invoking an access mode method of 2705 * any VarHandle whose access mode type is of the given type. 2706 * @since 9 2707 */ 2708 static public 2709 MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2710 return type.invokers().varHandleMethodExactInvoker(accessMode); 2711 } 2712 2713 /** 2714 * Produces a special <em>invoker method handle</em> which can be used to 2715 * invoke a signature-polymorphic access mode method on any VarHandle whose 2716 * associated access mode type is compatible with the given type. 2717 * The resulting invoker will have a type which is exactly equal to the 2718 * desired given type, except that it will accept an additional leading 2719 * argument of type {@code VarHandle}. 2720 * <p> 2721 * Before invoking its target, if the access mode type differs from the 2722 * desired given type, the invoker will apply reference casts as necessary 2723 * and box, unbox, or widen primitive values, as if by 2724 * {@link MethodHandle#asType asType}. Similarly, the return value will be 2725 * converted as necessary. 2726 * <p> 2727 * This method is equivalent to the following code (though it may be more 2728 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 2729 * 2730 * @param accessMode the VarHandle access mode 2731 * @param type the desired target type 2732 * @return a method handle suitable for invoking an access mode method of 2733 * any VarHandle whose access mode type is convertible to the given 2734 * type. 2735 * @since 9 2736 */ 2737 static public 2738 MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2739 return type.invokers().varHandleMethodInvoker(accessMode); 2740 } 2741 2742 static /*non-public*/ 2743 MethodHandle basicInvoker(MethodType type) { 2744 return type.invokers().basicInvoker(); 2745 } 2746 2747 /// method handle modification (creation from other method handles) 2748 2749 /** 2750 * Produces a method handle which adapts the type of the 2751 * given method handle to a new type by pairwise argument and return type conversion. 2752 * The original type and new type must have the same number of arguments. 2753 * The resulting method handle is guaranteed to report a type 2754 * which is equal to the desired new type. 2755 * <p> 2756 * If the original type and new type are equal, returns target. 2757 * <p> 2758 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 2759 * and some additional conversions are also applied if those conversions fail. 2760 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 2761 * if possible, before or instead of any conversions done by {@code asType}: 2762 * <ul> 2763 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 2764 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 2765 * (This treatment of interfaces follows the usage of the bytecode verifier.) 2766 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 2767 * the boolean is converted to a byte value, 1 for true, 0 for false. 2768 * (This treatment follows the usage of the bytecode verifier.) 2769 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 2770 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 2771 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 2772 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 2773 * then a Java casting conversion (JLS 5.5) is applied. 2774 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 2775 * widening and/or narrowing.) 2776 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 2777 * conversion will be applied at runtime, possibly followed 2778 * by a Java casting conversion (JLS 5.5) on the primitive value, 2779 * possibly followed by a conversion from byte to boolean by testing 2780 * the low-order bit. 2781 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 2782 * and if the reference is null at runtime, a zero value is introduced. 2783 * </ul> 2784 * @param target the method handle to invoke after arguments are retyped 2785 * @param newType the expected type of the new method handle 2786 * @return a method handle which delegates to the target after performing 2787 * any necessary argument conversions, and arranges for any 2788 * necessary return value conversions 2789 * @throws NullPointerException if either argument is null 2790 * @throws WrongMethodTypeException if the conversion cannot be made 2791 * @see MethodHandle#asType 2792 */ 2793 public static 2794 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 2795 explicitCastArgumentsChecks(target, newType); 2796 // use the asTypeCache when possible: 2797 MethodType oldType = target.type(); 2798 if (oldType == newType) return target; 2799 if (oldType.explicitCastEquivalentToAsType(newType)) { 2800 return target.asFixedArity().asType(newType); 2801 } 2802 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 2803 } 2804 2805 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 2806 if (target.type().parameterCount() != newType.parameterCount()) { 2807 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 2808 } 2809 } 2810 2811 /** 2812 * Produces a method handle which adapts the calling sequence of the 2813 * given method handle to a new type, by reordering the arguments. 2814 * The resulting method handle is guaranteed to report a type 2815 * which is equal to the desired new type. 2816 * <p> 2817 * The given array controls the reordering. 2818 * Call {@code #I} the number of incoming parameters (the value 2819 * {@code newType.parameterCount()}, and call {@code #O} the number 2820 * of outgoing parameters (the value {@code target.type().parameterCount()}). 2821 * Then the length of the reordering array must be {@code #O}, 2822 * and each element must be a non-negative number less than {@code #I}. 2823 * For every {@code N} less than {@code #O}, the {@code N}-th 2824 * outgoing argument will be taken from the {@code I}-th incoming 2825 * argument, where {@code I} is {@code reorder[N]}. 2826 * <p> 2827 * No argument or return value conversions are applied. 2828 * The type of each incoming argument, as determined by {@code newType}, 2829 * must be identical to the type of the corresponding outgoing parameter 2830 * or parameters in the target method handle. 2831 * The return type of {@code newType} must be identical to the return 2832 * type of the original target. 2833 * <p> 2834 * The reordering array need not specify an actual permutation. 2835 * An incoming argument will be duplicated if its index appears 2836 * more than once in the array, and an incoming argument will be dropped 2837 * if its index does not appear in the array. 2838 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 2839 * incoming arguments which are not mentioned in the reordering array 2840 * may be of any type, as determined only by {@code newType}. 2841 * <blockquote><pre>{@code 2842 import static java.lang.invoke.MethodHandles.*; 2843 import static java.lang.invoke.MethodType.*; 2844 ... 2845 MethodType intfn1 = methodType(int.class, int.class); 2846 MethodType intfn2 = methodType(int.class, int.class, int.class); 2847 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 2848 assert(sub.type().equals(intfn2)); 2849 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 2850 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 2851 assert((int)rsub.invokeExact(1, 100) == 99); 2852 MethodHandle add = ... (int x, int y) -> (x+y) ...; 2853 assert(add.type().equals(intfn2)); 2854 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 2855 assert(twice.type().equals(intfn1)); 2856 assert((int)twice.invokeExact(21) == 42); 2857 * }</pre></blockquote> 2858 * <p> 2859 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 2860 * variable-arity method handle}, even if the original target method handle was. 2861 * @param target the method handle to invoke after arguments are reordered 2862 * @param newType the expected type of the new method handle 2863 * @param reorder an index array which controls the reordering 2864 * @return a method handle which delegates to the target after it 2865 * drops unused arguments and moves and/or duplicates the other arguments 2866 * @throws NullPointerException if any argument is null 2867 * @throws IllegalArgumentException if the index array length is not equal to 2868 * the arity of the target, or if any index array element 2869 * not a valid index for a parameter of {@code newType}, 2870 * or if two corresponding parameter types in 2871 * {@code target.type()} and {@code newType} are not identical, 2872 */ 2873 public static 2874 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 2875 reorder = reorder.clone(); // get a private copy 2876 MethodType oldType = target.type(); 2877 permuteArgumentChecks(reorder, newType, oldType); 2878 // first detect dropped arguments and handle them separately 2879 int[] originalReorder = reorder; 2880 BoundMethodHandle result = target.rebind(); 2881 LambdaForm form = result.form; 2882 int newArity = newType.parameterCount(); 2883 // Normalize the reordering into a real permutation, 2884 // by removing duplicates and adding dropped elements. 2885 // This somewhat improves lambda form caching, as well 2886 // as simplifying the transform by breaking it up into steps. 2887 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 2888 if (ddIdx > 0) { 2889 // We found a duplicated entry at reorder[ddIdx]. 2890 // Example: (x,y,z)->asList(x,y,z) 2891 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 2892 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 2893 // The starred element corresponds to the argument 2894 // deleted by the dupArgumentForm transform. 2895 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 2896 boolean killFirst = false; 2897 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 2898 // Set killFirst if the dup is larger than an intervening position. 2899 // This will remove at least one inversion from the permutation. 2900 if (dupVal > val) killFirst = true; 2901 } 2902 if (!killFirst) { 2903 srcPos = dstPos; 2904 dstPos = ddIdx; 2905 } 2906 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 2907 assert (reorder[srcPos] == reorder[dstPos]); 2908 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 2909 // contract the reordering by removing the element at dstPos 2910 int tailPos = dstPos + 1; 2911 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 2912 reorder = Arrays.copyOf(reorder, reorder.length - 1); 2913 } else { 2914 int dropVal = ~ddIdx, insPos = 0; 2915 while (insPos < reorder.length && reorder[insPos] < dropVal) { 2916 // Find first element of reorder larger than dropVal. 2917 // This is where we will insert the dropVal. 2918 insPos += 1; 2919 } 2920 Class<?> ptype = newType.parameterType(dropVal); 2921 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 2922 oldType = oldType.insertParameterTypes(insPos, ptype); 2923 // expand the reordering by inserting an element at insPos 2924 int tailPos = insPos + 1; 2925 reorder = Arrays.copyOf(reorder, reorder.length + 1); 2926 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 2927 reorder[insPos] = dropVal; 2928 } 2929 assert (permuteArgumentChecks(reorder, newType, oldType)); 2930 } 2931 assert (reorder.length == newArity); // a perfect permutation 2932 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 2933 form = form.editor().permuteArgumentsForm(1, reorder); 2934 if (newType == result.type() && form == result.internalForm()) 2935 return result; 2936 return result.copyWith(newType, form); 2937 } 2938 2939 /** 2940 * Return an indication of any duplicate or omission in reorder. 2941 * If the reorder contains a duplicate entry, return the index of the second occurrence. 2942 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 2943 * Otherwise, return zero. 2944 * If an element not in [0..newArity-1] is encountered, return reorder.length. 2945 */ 2946 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 2947 final int BIT_LIMIT = 63; // max number of bits in bit mask 2948 if (newArity < BIT_LIMIT) { 2949 long mask = 0; 2950 for (int i = 0; i < reorder.length; i++) { 2951 int arg = reorder[i]; 2952 if (arg >= newArity) { 2953 return reorder.length; 2954 } 2955 long bit = 1L << arg; 2956 if ((mask & bit) != 0) { 2957 return i; // >0 indicates a dup 2958 } 2959 mask |= bit; 2960 } 2961 if (mask == (1L << newArity) - 1) { 2962 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 2963 return 0; 2964 } 2965 // find first zero 2966 long zeroBit = Long.lowestOneBit(~mask); 2967 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 2968 assert(zeroPos <= newArity); 2969 if (zeroPos == newArity) { 2970 return 0; 2971 } 2972 return ~zeroPos; 2973 } else { 2974 // same algorithm, different bit set 2975 BitSet mask = new BitSet(newArity); 2976 for (int i = 0; i < reorder.length; i++) { 2977 int arg = reorder[i]; 2978 if (arg >= newArity) { 2979 return reorder.length; 2980 } 2981 if (mask.get(arg)) { 2982 return i; // >0 indicates a dup 2983 } 2984 mask.set(arg); 2985 } 2986 int zeroPos = mask.nextClearBit(0); 2987 assert(zeroPos <= newArity); 2988 if (zeroPos == newArity) { 2989 return 0; 2990 } 2991 return ~zeroPos; 2992 } 2993 } 2994 2995 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 2996 if (newType.returnType() != oldType.returnType()) 2997 throw newIllegalArgumentException("return types do not match", 2998 oldType, newType); 2999 if (reorder.length == oldType.parameterCount()) { 3000 int limit = newType.parameterCount(); 3001 boolean bad = false; 3002 for (int j = 0; j < reorder.length; j++) { 3003 int i = reorder[j]; 3004 if (i < 0 || i >= limit) { 3005 bad = true; break; 3006 } 3007 Class<?> src = newType.parameterType(i); 3008 Class<?> dst = oldType.parameterType(j); 3009 if (src != dst) 3010 throw newIllegalArgumentException("parameter types do not match after reorder", 3011 oldType, newType); 3012 } 3013 if (!bad) return true; 3014 } 3015 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 3016 } 3017 3018 /** 3019 * Produces a method handle of the requested return type which returns the given 3020 * constant value every time it is invoked. 3021 * <p> 3022 * Before the method handle is returned, the passed-in value is converted to the requested type. 3023 * If the requested type is primitive, widening primitive conversions are attempted, 3024 * else reference conversions are attempted. 3025 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 3026 * @param type the return type of the desired method handle 3027 * @param value the value to return 3028 * @return a method handle of the given return type and no arguments, which always returns the given value 3029 * @throws NullPointerException if the {@code type} argument is null 3030 * @throws ClassCastException if the value cannot be converted to the required return type 3031 * @throws IllegalArgumentException if the given type is {@code void.class} 3032 */ 3033 public static 3034 MethodHandle constant(Class<?> type, Object value) { 3035 if (type.isPrimitive()) { 3036 if (type == void.class) 3037 throw newIllegalArgumentException("void type"); 3038 Wrapper w = Wrapper.forPrimitiveType(type); 3039 value = w.convert(value, type); 3040 if (w.zero().equals(value)) 3041 return zero(w, type); 3042 return insertArguments(identity(type), 0, value); 3043 } else { 3044 if (value == null) 3045 return zero(Wrapper.OBJECT, type); 3046 return identity(type).bindTo(value); 3047 } 3048 } 3049 3050 /** 3051 * Produces a method handle which returns its sole argument when invoked. 3052 * @param type the type of the sole parameter and return value of the desired method handle 3053 * @return a unary method handle which accepts and returns the given type 3054 * @throws NullPointerException if the argument is null 3055 * @throws IllegalArgumentException if the given type is {@code void.class} 3056 */ 3057 public static 3058 MethodHandle identity(Class<?> type) { 3059 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 3060 int pos = btw.ordinal(); 3061 MethodHandle ident = IDENTITY_MHS[pos]; 3062 if (ident == null) { 3063 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 3064 } 3065 if (ident.type().returnType() == type) 3066 return ident; 3067 // something like identity(Foo.class); do not bother to intern these 3068 assert (btw == Wrapper.OBJECT); 3069 return makeIdentity(type); 3070 } 3071 3072 /** 3073 * Produces a constant method handle of the requested return type which 3074 * returns the default value for that type every time it is invoked. 3075 * The resulting constant method handle will have no side effects. 3076 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 3077 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 3078 * since {@code explicitCastArguments} converts {@code null} to default values. 3079 * @param type the expected return type of the desired method handle 3080 * @return a constant method handle that takes no arguments 3081 * and returns the default value of the given type (or void, if the type is void) 3082 * @throws NullPointerException if the argument is null 3083 * @see MethodHandles#constant 3084 * @see MethodHandles#empty 3085 * @see MethodHandles#explicitCastArguments 3086 * @since 9 3087 */ 3088 public static MethodHandle zero(Class<?> type) { 3089 Objects.requireNonNull(type); 3090 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 3091 } 3092 3093 private static MethodHandle identityOrVoid(Class<?> type) { 3094 return type == void.class ? zero(type) : identity(type); 3095 } 3096 3097 /** 3098 * Produces a method handle of the requested type which ignores any arguments, does nothing, 3099 * and returns a suitable default depending on the return type. 3100 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 3101 * <p>The returned method handle is equivalent to 3102 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 3103 * <p> 3104 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 3105 * {@code guardWithTest(pred, target, empty(target.type())}. 3106 * @param type the type of the desired method handle 3107 * @return a constant method handle of the given type, which returns a default value of the given return type 3108 * @throws NullPointerException if the argument is null 3109 * @see MethodHandles#zero 3110 * @see MethodHandles#constant 3111 * @since 9 3112 */ 3113 public static MethodHandle empty(MethodType type) { 3114 Objects.requireNonNull(type); 3115 return dropArguments(zero(type.returnType()), 0, type.parameterList()); 3116 } 3117 3118 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length]; 3119 private static MethodHandle makeIdentity(Class<?> ptype) { 3120 MethodType mtype = methodType(ptype, ptype); 3121 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 3122 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 3123 } 3124 3125 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 3126 int pos = btw.ordinal(); 3127 MethodHandle zero = ZERO_MHS[pos]; 3128 if (zero == null) { 3129 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 3130 } 3131 if (zero.type().returnType() == rtype) 3132 return zero; 3133 assert(btw == Wrapper.OBJECT); 3134 return makeZero(rtype); 3135 } 3136 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length]; 3137 private static MethodHandle makeZero(Class<?> rtype) { 3138 MethodType mtype = methodType(rtype); 3139 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 3140 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 3141 } 3142 3143 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 3144 // Simulate a CAS, to avoid racy duplication of results. 3145 MethodHandle prev = cache[pos]; 3146 if (prev != null) return prev; 3147 return cache[pos] = value; 3148 } 3149 3150 /** 3151 * Provides a target method handle with one or more <em>bound arguments</em> 3152 * in advance of the method handle's invocation. 3153 * The formal parameters to the target corresponding to the bound 3154 * arguments are called <em>bound parameters</em>. 3155 * Returns a new method handle which saves away the bound arguments. 3156 * When it is invoked, it receives arguments for any non-bound parameters, 3157 * binds the saved arguments to their corresponding parameters, 3158 * and calls the original target. 3159 * <p> 3160 * The type of the new method handle will drop the types for the bound 3161 * parameters from the original target type, since the new method handle 3162 * will no longer require those arguments to be supplied by its callers. 3163 * <p> 3164 * Each given argument object must match the corresponding bound parameter type. 3165 * If a bound parameter type is a primitive, the argument object 3166 * must be a wrapper, and will be unboxed to produce the primitive value. 3167 * <p> 3168 * The {@code pos} argument selects which parameters are to be bound. 3169 * It may range between zero and <i>N-L</i> (inclusively), 3170 * where <i>N</i> is the arity of the target method handle 3171 * and <i>L</i> is the length of the values array. 3172 * <p> 3173 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3174 * variable-arity method handle}, even if the original target method handle was. 3175 * @param target the method handle to invoke after the argument is inserted 3176 * @param pos where to insert the argument (zero for the first) 3177 * @param values the series of arguments to insert 3178 * @return a method handle which inserts an additional argument, 3179 * before calling the original method handle 3180 * @throws NullPointerException if the target or the {@code values} array is null 3181 * @see MethodHandle#bindTo 3182 */ 3183 public static 3184 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 3185 int insCount = values.length; 3186 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 3187 if (insCount == 0) return target; 3188 BoundMethodHandle result = target.rebind(); 3189 for (int i = 0; i < insCount; i++) { 3190 Object value = values[i]; 3191 Class<?> ptype = ptypes[pos+i]; 3192 if (ptype.isPrimitive()) { 3193 result = insertArgumentPrimitive(result, pos, ptype, value); 3194 } else { 3195 value = ptype.cast(value); // throw CCE if needed 3196 result = result.bindArgumentL(pos, value); 3197 } 3198 } 3199 return result; 3200 } 3201 3202 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 3203 Class<?> ptype, Object value) { 3204 Wrapper w = Wrapper.forPrimitiveType(ptype); 3205 // perform unboxing and/or primitive conversion 3206 value = w.convert(value, ptype); 3207 switch (w) { 3208 case INT: return result.bindArgumentI(pos, (int)value); 3209 case LONG: return result.bindArgumentJ(pos, (long)value); 3210 case FLOAT: return result.bindArgumentF(pos, (float)value); 3211 case DOUBLE: return result.bindArgumentD(pos, (double)value); 3212 default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 3213 } 3214 } 3215 3216 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 3217 MethodType oldType = target.type(); 3218 int outargs = oldType.parameterCount(); 3219 int inargs = outargs - insCount; 3220 if (inargs < 0) 3221 throw newIllegalArgumentException("too many values to insert"); 3222 if (pos < 0 || pos > inargs) 3223 throw newIllegalArgumentException("no argument type to append"); 3224 return oldType.ptypes(); 3225 } 3226 3227 /** 3228 * Produces a method handle which will discard some dummy arguments 3229 * before calling some other specified <i>target</i> method handle. 3230 * The type of the new method handle will be the same as the target's type, 3231 * except it will also include the dummy argument types, 3232 * at some given position. 3233 * <p> 3234 * The {@code pos} argument may range between zero and <i>N</i>, 3235 * where <i>N</i> is the arity of the target. 3236 * If {@code pos} is zero, the dummy arguments will precede 3237 * the target's real arguments; if {@code pos} is <i>N</i> 3238 * they will come after. 3239 * <p> 3240 * <b>Example:</b> 3241 * <blockquote><pre>{@code 3242 import static java.lang.invoke.MethodHandles.*; 3243 import static java.lang.invoke.MethodType.*; 3244 ... 3245 MethodHandle cat = lookup().findVirtual(String.class, 3246 "concat", methodType(String.class, String.class)); 3247 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3248 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 3249 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 3250 assertEquals(bigType, d0.type()); 3251 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 3252 * }</pre></blockquote> 3253 * <p> 3254 * This method is also equivalent to the following code: 3255 * <blockquote><pre> 3256 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 3257 * </pre></blockquote> 3258 * @param target the method handle to invoke after the arguments are dropped 3259 * @param valueTypes the type(s) of the argument(s) to drop 3260 * @param pos position of first argument to drop (zero for the leftmost) 3261 * @return a method handle which drops arguments of the given types, 3262 * before calling the original method handle 3263 * @throws NullPointerException if the target is null, 3264 * or if the {@code valueTypes} list or any of its elements is null 3265 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3266 * or if {@code pos} is negative or greater than the arity of the target, 3267 * or if the new method handle's type would have too many parameters 3268 */ 3269 public static 3270 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3271 MethodType oldType = target.type(); // get NPE 3272 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 3273 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 3274 if (dropped == 0) return target; 3275 BoundMethodHandle result = target.rebind(); 3276 LambdaForm lform = result.form; 3277 int insertFormArg = 1 + pos; 3278 for (Class<?> ptype : valueTypes) { 3279 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 3280 } 3281 result = result.copyWith(newType, lform); 3282 return result; 3283 } 3284 3285 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { 3286 int dropped = valueTypes.size(); 3287 MethodType.checkSlotCount(dropped); 3288 int outargs = oldType.parameterCount(); 3289 int inargs = outargs + dropped; 3290 if (pos < 0 || pos > outargs) 3291 throw newIllegalArgumentException("no argument type to remove" 3292 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 3293 ); 3294 return dropped; 3295 } 3296 3297 /** 3298 * Produces a method handle which will discard some dummy arguments 3299 * before calling some other specified <i>target</i> method handle. 3300 * The type of the new method handle will be the same as the target's type, 3301 * except it will also include the dummy argument types, 3302 * at some given position. 3303 * <p> 3304 * The {@code pos} argument may range between zero and <i>N</i>, 3305 * where <i>N</i> is the arity of the target. 3306 * If {@code pos} is zero, the dummy arguments will precede 3307 * the target's real arguments; if {@code pos} is <i>N</i> 3308 * they will come after. 3309 * @apiNote 3310 * <blockquote><pre>{@code 3311 import static java.lang.invoke.MethodHandles.*; 3312 import static java.lang.invoke.MethodType.*; 3313 ... 3314 MethodHandle cat = lookup().findVirtual(String.class, 3315 "concat", methodType(String.class, String.class)); 3316 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3317 MethodHandle d0 = dropArguments(cat, 0, String.class); 3318 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 3319 MethodHandle d1 = dropArguments(cat, 1, String.class); 3320 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 3321 MethodHandle d2 = dropArguments(cat, 2, String.class); 3322 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 3323 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 3324 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 3325 * }</pre></blockquote> 3326 * <p> 3327 * This method is also equivalent to the following code: 3328 * <blockquote><pre> 3329 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 3330 * </pre></blockquote> 3331 * @param target the method handle to invoke after the arguments are dropped 3332 * @param valueTypes the type(s) of the argument(s) to drop 3333 * @param pos position of first argument to drop (zero for the leftmost) 3334 * @return a method handle which drops arguments of the given types, 3335 * before calling the original method handle 3336 * @throws NullPointerException if the target is null, 3337 * or if the {@code valueTypes} array or any of its elements is null 3338 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3339 * or if {@code pos} is negative or greater than the arity of the target, 3340 * or if the new method handle's type would have 3341 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3342 */ 3343 public static 3344 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 3345 return dropArguments(target, pos, Arrays.asList(valueTypes)); 3346 } 3347 3348 // private version which allows caller some freedom with error handling 3349 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, 3350 boolean nullOnFailure) { 3351 List<Class<?>> oldTypes = target.type().parameterList(); 3352 int match = oldTypes.size(); 3353 if (skip != 0) { 3354 if (skip < 0 || skip > match) { 3355 throw newIllegalArgumentException("illegal skip", skip, target); 3356 } 3357 oldTypes = oldTypes.subList(skip, match); 3358 match -= skip; 3359 } 3360 List<Class<?>> addTypes = newTypes; 3361 int add = addTypes.size(); 3362 if (pos != 0) { 3363 if (pos < 0 || pos > add) { 3364 throw newIllegalArgumentException("illegal pos", pos, newTypes); 3365 } 3366 addTypes = addTypes.subList(pos, add); 3367 add -= pos; assert(addTypes.size() == add); 3368 } 3369 // Do not add types which already match the existing arguments. 3370 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { 3371 if (nullOnFailure) { 3372 return null; 3373 } 3374 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); 3375 } 3376 addTypes = addTypes.subList(match, add); 3377 add -= match; assert(addTypes.size() == add); 3378 // newTypes: ( P*[pos], M*[match], A*[add] ) 3379 // target: ( S*[skip], M*[match] ) 3380 MethodHandle adapter = target; 3381 if (add > 0) { 3382 adapter = dropArguments(adapter, skip+ match, addTypes); 3383 } 3384 // adapter: (S*[skip], M*[match], A*[add] ) 3385 if (pos > 0) { 3386 adapter = dropArguments(adapter, skip, newTypes.subList(0, pos)); 3387 } 3388 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 3389 return adapter; 3390 } 3391 3392 /** 3393 * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments. 3394 * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored. 3395 * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list, 3396 * at the given position. 3397 * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding 3398 * positions of the target method handle's parameters, as if by {@link #dropArguments}. 3399 * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip}, 3400 * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the 3401 * target list.) 3402 * The target's return type will be unchanged. 3403 * @apiNote 3404 * Two method handles whose argument lists are "effectively identical" (i.e., identical 3405 * in a common prefix) may be mutually converted to a common type 3406 * by two calls to {@code dropArgumentsToMatch}, as follows: 3407 * <blockquote><pre>{@code 3408 import static java.lang.invoke.MethodHandles.*; 3409 import static java.lang.invoke.MethodType.*; 3410 ... 3411 ... 3412 MethodHandle h0 = constant(boolean.class, true); 3413 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 3414 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 3415 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 3416 if (h1.type().parameterCount() < h2.type().parameterCount()) 3417 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 3418 else 3419 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 3420 MethodHandle h3 = guardWithTest(h0, h1, h2); 3421 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 3422 * }</pre></blockquote> 3423 * @param target the method handle to adapt 3424 * @param skip number of targets parameters to disregard (they will be unchanged) 3425 * @param newTypes the desired argument list of the method handle 3426 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 3427 * @return a possibly adapted method handle 3428 * @throws NullPointerException if either argument is null 3429 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 3430 * or if {@code skip} is negative or greater than the arity of the target, 3431 * or if {@code pos} is negative or greater than the newTypes list size, 3432 * or if the non-skipped target parameter types match the new types at {@code pos} 3433 * @since 9 3434 */ 3435 public static 3436 MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 3437 Objects.requireNonNull(target); 3438 Objects.requireNonNull(newTypes); 3439 return dropArgumentsToMatch(target, skip, newTypes, pos, false); 3440 } 3441 3442 /** 3443 * Adapts a target method handle by pre-processing 3444 * one or more of its arguments, each with its own unary filter function, 3445 * and then calling the target with each pre-processed argument 3446 * replaced by the result of its corresponding filter function. 3447 * <p> 3448 * The pre-processing is performed by one or more method handles, 3449 * specified in the elements of the {@code filters} array. 3450 * The first element of the filter array corresponds to the {@code pos} 3451 * argument of the target, and so on in sequence. 3452 * <p> 3453 * Null arguments in the array are treated as identity functions, 3454 * and the corresponding arguments left unchanged. 3455 * (If there are no non-null elements in the array, the original target is returned.) 3456 * Each filter is applied to the corresponding argument of the adapter. 3457 * <p> 3458 * If a filter {@code F} applies to the {@code N}th argument of 3459 * the target, then {@code F} must be a method handle which 3460 * takes exactly one argument. The type of {@code F}'s sole argument 3461 * replaces the corresponding argument type of the target 3462 * in the resulting adapted method handle. 3463 * The return type of {@code F} must be identical to the corresponding 3464 * parameter type of the target. 3465 * <p> 3466 * It is an error if there are elements of {@code filters} 3467 * (null or not) 3468 * which do not correspond to argument positions in the target. 3469 * <p><b>Example:</b> 3470 * <blockquote><pre>{@code 3471 import static java.lang.invoke.MethodHandles.*; 3472 import static java.lang.invoke.MethodType.*; 3473 ... 3474 MethodHandle cat = lookup().findVirtual(String.class, 3475 "concat", methodType(String.class, String.class)); 3476 MethodHandle upcase = lookup().findVirtual(String.class, 3477 "toUpperCase", methodType(String.class)); 3478 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3479 MethodHandle f0 = filterArguments(cat, 0, upcase); 3480 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 3481 MethodHandle f1 = filterArguments(cat, 1, upcase); 3482 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 3483 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 3484 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 3485 * }</pre></blockquote> 3486 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3487 * denotes the return type of both the {@code target} and resulting adapter. 3488 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 3489 * of the parameters and arguments that precede and follow the filter position 3490 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 3491 * values of the filtered parameters and arguments; they also represent the 3492 * return types of the {@code filter[i]} handles. The latter accept arguments 3493 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 3494 * the resulting adapter. 3495 * <blockquote><pre>{@code 3496 * T target(P... p, A[i]... a[i], B... b); 3497 * A[i] filter[i](V[i]); 3498 * T adapter(P... p, V[i]... v[i], B... b) { 3499 * return target(p..., filter[i](v[i])..., b...); 3500 * } 3501 * }</pre></blockquote> 3502 * <p> 3503 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3504 * variable-arity method handle}, even if the original target method handle was. 3505 * 3506 * @param target the method handle to invoke after arguments are filtered 3507 * @param pos the position of the first argument to filter 3508 * @param filters method handles to call initially on filtered arguments 3509 * @return method handle which incorporates the specified argument filtering logic 3510 * @throws NullPointerException if the target is null 3511 * or if the {@code filters} array is null 3512 * @throws IllegalArgumentException if a non-null element of {@code filters} 3513 * does not match a corresponding argument type of target as described above, 3514 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 3515 * or if the resulting method handle's type would have 3516 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3517 */ 3518 public static 3519 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 3520 filterArgumentsCheckArity(target, pos, filters); 3521 MethodHandle adapter = target; 3522 int curPos = pos-1; // pre-incremented 3523 for (MethodHandle filter : filters) { 3524 curPos += 1; 3525 if (filter == null) continue; // ignore null elements of filters 3526 adapter = filterArgument(adapter, curPos, filter); 3527 } 3528 return adapter; 3529 } 3530 3531 /*non-public*/ static 3532 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 3533 filterArgumentChecks(target, pos, filter); 3534 MethodType targetType = target.type(); 3535 MethodType filterType = filter.type(); 3536 BoundMethodHandle result = target.rebind(); 3537 Class<?> newParamType = filterType.parameterType(0); 3538 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 3539 MethodType newType = targetType.changeParameterType(pos, newParamType); 3540 result = result.copyWithExtendL(newType, lform, filter); 3541 return result; 3542 } 3543 3544 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 3545 MethodType targetType = target.type(); 3546 int maxPos = targetType.parameterCount(); 3547 if (pos + filters.length > maxPos) 3548 throw newIllegalArgumentException("too many filters"); 3549 } 3550 3551 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3552 MethodType targetType = target.type(); 3553 MethodType filterType = filter.type(); 3554 if (filterType.parameterCount() != 1 3555 || filterType.returnType() != targetType.parameterType(pos)) 3556 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3557 } 3558 3559 /** 3560 * Adapts a target method handle by pre-processing 3561 * a sub-sequence of its arguments with a filter (another method handle). 3562 * The pre-processed arguments are replaced by the result (if any) of the 3563 * filter function. 3564 * The target is then called on the modified (usually shortened) argument list. 3565 * <p> 3566 * If the filter returns a value, the target must accept that value as 3567 * its argument in position {@code pos}, preceded and/or followed by 3568 * any arguments not passed to the filter. 3569 * If the filter returns void, the target must accept all arguments 3570 * not passed to the filter. 3571 * No arguments are reordered, and a result returned from the filter 3572 * replaces (in order) the whole subsequence of arguments originally 3573 * passed to the adapter. 3574 * <p> 3575 * The argument types (if any) of the filter 3576 * replace zero or one argument types of the target, at position {@code pos}, 3577 * in the resulting adapted method handle. 3578 * The return type of the filter (if any) must be identical to the 3579 * argument type of the target at position {@code pos}, and that target argument 3580 * is supplied by the return value of the filter. 3581 * <p> 3582 * In all cases, {@code pos} must be greater than or equal to zero, and 3583 * {@code pos} must also be less than or equal to the target's arity. 3584 * <p><b>Example:</b> 3585 * <blockquote><pre>{@code 3586 import static java.lang.invoke.MethodHandles.*; 3587 import static java.lang.invoke.MethodType.*; 3588 ... 3589 MethodHandle deepToString = publicLookup() 3590 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 3591 3592 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 3593 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 3594 3595 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 3596 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 3597 3598 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 3599 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 3600 assertEquals("[top, [up, down], strange]", 3601 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 3602 3603 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 3604 assertEquals("[top, [up, down], [strange]]", 3605 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 3606 3607 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 3608 assertEquals("[top, [[up, down, strange], charm], bottom]", 3609 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 3610 * }</pre></blockquote> 3611 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3612 * represents the return type of the {@code target} and resulting adapter. 3613 * {@code V}/{@code v} stand for the return type and value of the 3614 * {@code filter}, which are also found in the signature and arguments of 3615 * the {@code target}, respectively, unless {@code V} is {@code void}. 3616 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 3617 * and values preceding and following the collection position, {@code pos}, 3618 * in the {@code target}'s signature. They also turn up in the resulting 3619 * adapter's signature and arguments, where they surround 3620 * {@code B}/{@code b}, which represent the parameter types and arguments 3621 * to the {@code filter} (if any). 3622 * <blockquote><pre>{@code 3623 * T target(A...,V,C...); 3624 * V filter(B...); 3625 * T adapter(A... a,B... b,C... c) { 3626 * V v = filter(b...); 3627 * return target(a...,v,c...); 3628 * } 3629 * // and if the filter has no arguments: 3630 * T target2(A...,V,C...); 3631 * V filter2(); 3632 * T adapter2(A... a,C... c) { 3633 * V v = filter2(); 3634 * return target2(a...,v,c...); 3635 * } 3636 * // and if the filter has a void return: 3637 * T target3(A...,C...); 3638 * void filter3(B...); 3639 * T adapter3(A... a,B... b,C... c) { 3640 * filter3(b...); 3641 * return target3(a...,c...); 3642 * } 3643 * }</pre></blockquote> 3644 * <p> 3645 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 3646 * one which first "folds" the affected arguments, and then drops them, in separate 3647 * steps as follows: 3648 * <blockquote><pre>{@code 3649 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 3650 * mh = MethodHandles.foldArguments(mh, coll); //step 1 3651 * }</pre></blockquote> 3652 * If the target method handle consumes no arguments besides than the result 3653 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 3654 * is equivalent to {@code filterReturnValue(coll, mh)}. 3655 * If the filter method handle {@code coll} consumes one argument and produces 3656 * a non-void result, then {@code collectArguments(mh, N, coll)} 3657 * is equivalent to {@code filterArguments(mh, N, coll)}. 3658 * Other equivalences are possible but would require argument permutation. 3659 * <p> 3660 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3661 * variable-arity method handle}, even if the original target method handle was. 3662 * 3663 * @param target the method handle to invoke after filtering the subsequence of arguments 3664 * @param pos the position of the first adapter argument to pass to the filter, 3665 * and/or the target argument which receives the result of the filter 3666 * @param filter method handle to call on the subsequence of arguments 3667 * @return method handle which incorporates the specified argument subsequence filtering logic 3668 * @throws NullPointerException if either argument is null 3669 * @throws IllegalArgumentException if the return type of {@code filter} 3670 * is non-void and is not the same as the {@code pos} argument of the target, 3671 * or if {@code pos} is not between 0 and the target's arity, inclusive, 3672 * or if the resulting method handle's type would have 3673 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3674 * @see MethodHandles#foldArguments 3675 * @see MethodHandles#filterArguments 3676 * @see MethodHandles#filterReturnValue 3677 */ 3678 public static 3679 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 3680 MethodType newType = collectArgumentsChecks(target, pos, filter); 3681 MethodType collectorType = filter.type(); 3682 BoundMethodHandle result = target.rebind(); 3683 LambdaForm lform; 3684 if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { 3685 lform = result.editor().collectArgumentArrayForm(1 + pos, filter); 3686 if (lform != null) { 3687 return result.copyWith(newType, lform); 3688 } 3689 } 3690 lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 3691 return result.copyWithExtendL(newType, lform, filter); 3692 } 3693 3694 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3695 MethodType targetType = target.type(); 3696 MethodType filterType = filter.type(); 3697 Class<?> rtype = filterType.returnType(); 3698 List<Class<?>> filterArgs = filterType.parameterList(); 3699 if (rtype == void.class) { 3700 return targetType.insertParameterTypes(pos, filterArgs); 3701 } 3702 if (rtype != targetType.parameterType(pos)) { 3703 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3704 } 3705 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); 3706 } 3707 3708 /** 3709 * Adapts a target method handle by post-processing 3710 * its return value (if any) with a filter (another method handle). 3711 * The result of the filter is returned from the adapter. 3712 * <p> 3713 * If the target returns a value, the filter must accept that value as 3714 * its only argument. 3715 * If the target returns void, the filter must accept no arguments. 3716 * <p> 3717 * The return type of the filter 3718 * replaces the return type of the target 3719 * in the resulting adapted method handle. 3720 * The argument type of the filter (if any) must be identical to the 3721 * return type of the target. 3722 * <p><b>Example:</b> 3723 * <blockquote><pre>{@code 3724 import static java.lang.invoke.MethodHandles.*; 3725 import static java.lang.invoke.MethodType.*; 3726 ... 3727 MethodHandle cat = lookup().findVirtual(String.class, 3728 "concat", methodType(String.class, String.class)); 3729 MethodHandle length = lookup().findVirtual(String.class, 3730 "length", methodType(int.class)); 3731 System.out.println((String) cat.invokeExact("x", "y")); // xy 3732 MethodHandle f0 = filterReturnValue(cat, length); 3733 System.out.println((int) f0.invokeExact("x", "y")); // 2 3734 * }</pre></blockquote> 3735 * <p>Here is pseudocode for the resulting adapter. In the code, 3736 * {@code T}/{@code t} represent the result type and value of the 3737 * {@code target}; {@code V}, the result type of the {@code filter}; and 3738 * {@code A}/{@code a}, the types and values of the parameters and arguments 3739 * of the {@code target} as well as the resulting adapter. 3740 * <blockquote><pre>{@code 3741 * T target(A...); 3742 * V filter(T); 3743 * V adapter(A... a) { 3744 * T t = target(a...); 3745 * return filter(t); 3746 * } 3747 * // and if the target has a void return: 3748 * void target2(A...); 3749 * V filter2(); 3750 * V adapter2(A... a) { 3751 * target2(a...); 3752 * return filter2(); 3753 * } 3754 * // and if the filter has a void return: 3755 * T target3(A...); 3756 * void filter3(V); 3757 * void adapter3(A... a) { 3758 * T t = target3(a...); 3759 * filter3(t); 3760 * } 3761 * }</pre></blockquote> 3762 * <p> 3763 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3764 * variable-arity method handle}, even if the original target method handle was. 3765 * @param target the method handle to invoke before filtering the return value 3766 * @param filter method handle to call on the return value 3767 * @return method handle which incorporates the specified return value filtering logic 3768 * @throws NullPointerException if either argument is null 3769 * @throws IllegalArgumentException if the argument list of {@code filter} 3770 * does not match the return type of target as described above 3771 */ 3772 public static 3773 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 3774 MethodType targetType = target.type(); 3775 MethodType filterType = filter.type(); 3776 filterReturnValueChecks(targetType, filterType); 3777 BoundMethodHandle result = target.rebind(); 3778 BasicType rtype = BasicType.basicType(filterType.returnType()); 3779 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 3780 MethodType newType = targetType.changeReturnType(filterType.returnType()); 3781 result = result.copyWithExtendL(newType, lform, filter); 3782 return result; 3783 } 3784 3785 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 3786 Class<?> rtype = targetType.returnType(); 3787 int filterValues = filterType.parameterCount(); 3788 if (filterValues == 0 3789 ? (rtype != void.class) 3790 : (rtype != filterType.parameterType(0))) 3791 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3792 } 3793 3794 /** 3795 * Adapts a target method handle by pre-processing 3796 * some of its arguments, and then calling the target with 3797 * the result of the pre-processing, inserted into the original 3798 * sequence of arguments. 3799 * <p> 3800 * The pre-processing is performed by {@code combiner}, a second method handle. 3801 * Of the arguments passed to the adapter, the first {@code N} arguments 3802 * are copied to the combiner, which is then called. 3803 * (Here, {@code N} is defined as the parameter count of the combiner.) 3804 * After this, control passes to the target, with any result 3805 * from the combiner inserted before the original {@code N} incoming 3806 * arguments. 3807 * <p> 3808 * If the combiner returns a value, the first parameter type of the target 3809 * must be identical with the return type of the combiner, and the next 3810 * {@code N} parameter types of the target must exactly match the parameters 3811 * of the combiner. 3812 * <p> 3813 * If the combiner has a void return, no result will be inserted, 3814 * and the first {@code N} parameter types of the target 3815 * must exactly match the parameters of the combiner. 3816 * <p> 3817 * The resulting adapter is the same type as the target, except that the 3818 * first parameter type is dropped, 3819 * if it corresponds to the result of the combiner. 3820 * <p> 3821 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 3822 * that either the combiner or the target does not wish to receive. 3823 * If some of the incoming arguments are destined only for the combiner, 3824 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 3825 * arguments will not need to be live on the stack on entry to the 3826 * target.) 3827 * <p><b>Example:</b> 3828 * <blockquote><pre>{@code 3829 import static java.lang.invoke.MethodHandles.*; 3830 import static java.lang.invoke.MethodType.*; 3831 ... 3832 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 3833 "println", methodType(void.class, String.class)) 3834 .bindTo(System.out); 3835 MethodHandle cat = lookup().findVirtual(String.class, 3836 "concat", methodType(String.class, String.class)); 3837 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 3838 MethodHandle catTrace = foldArguments(cat, trace); 3839 // also prints "boo": 3840 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 3841 * }</pre></blockquote> 3842 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3843 * represents the result type of the {@code target} and resulting adapter. 3844 * {@code V}/{@code v} represent the type and value of the parameter and argument 3845 * of {@code target} that precedes the folding position; {@code V} also is 3846 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 3847 * types and values of the {@code N} parameters and arguments at the folding 3848 * position. {@code B}/{@code b} represent the types and values of the 3849 * {@code target} parameters and arguments that follow the folded parameters 3850 * and arguments. 3851 * <blockquote><pre>{@code 3852 * // there are N arguments in A... 3853 * T target(V, A[N]..., B...); 3854 * V combiner(A...); 3855 * T adapter(A... a, B... b) { 3856 * V v = combiner(a...); 3857 * return target(v, a..., b...); 3858 * } 3859 * // and if the combiner has a void return: 3860 * T target2(A[N]..., B...); 3861 * void combiner2(A...); 3862 * T adapter2(A... a, B... b) { 3863 * combiner2(a...); 3864 * return target2(a..., b...); 3865 * } 3866 * }</pre></blockquote> 3867 * <p> 3868 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3869 * variable-arity method handle}, even if the original target method handle was. 3870 * @param target the method handle to invoke after arguments are combined 3871 * @param combiner method handle to call initially on the incoming arguments 3872 * @return method handle which incorporates the specified argument folding logic 3873 * @throws NullPointerException if either argument is null 3874 * @throws IllegalArgumentException if {@code combiner}'s return type 3875 * is non-void and not the same as the first argument type of 3876 * the target, or if the initial {@code N} argument types 3877 * of the target 3878 * (skipping one matching the {@code combiner}'s return type) 3879 * are not identical with the argument types of {@code combiner} 3880 */ 3881 public static 3882 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 3883 return foldArguments(target, 0, combiner); 3884 } 3885 3886 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 3887 int foldArgs = combinerType.parameterCount(); 3888 Class<?> rtype = combinerType.returnType(); 3889 int foldVals = rtype == void.class ? 0 : 1; 3890 int afterInsertPos = foldPos + foldVals; 3891 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 3892 if (ok && !(combinerType.parameterList() 3893 .equals(targetType.parameterList().subList(afterInsertPos, 3894 afterInsertPos + foldArgs)))) 3895 ok = false; 3896 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 3897 ok = false; 3898 if (!ok) 3899 throw misMatchedTypes("target and combiner types", targetType, combinerType); 3900 return rtype; 3901 } 3902 3903 /** 3904 * Makes a method handle which adapts a target method handle, 3905 * by guarding it with a test, a boolean-valued method handle. 3906 * If the guard fails, a fallback handle is called instead. 3907 * All three method handles must have the same corresponding 3908 * argument and return types, except that the return type 3909 * of the test must be boolean, and the test is allowed 3910 * to have fewer arguments than the other two method handles. 3911 * <p> 3912 * Here is pseudocode for the resulting adapter. In the code, {@code T} 3913 * represents the uniform result type of the three involved handles; 3914 * {@code A}/{@code a}, the types and values of the {@code target} 3915 * parameters and arguments that are consumed by the {@code test}; and 3916 * {@code B}/{@code b}, those types and values of the {@code target} 3917 * parameters and arguments that are not consumed by the {@code test}. 3918 * <blockquote><pre>{@code 3919 * boolean test(A...); 3920 * T target(A...,B...); 3921 * T fallback(A...,B...); 3922 * T adapter(A... a,B... b) { 3923 * if (test(a...)) 3924 * return target(a..., b...); 3925 * else 3926 * return fallback(a..., b...); 3927 * } 3928 * }</pre></blockquote> 3929 * Note that the test arguments ({@code a...} in the pseudocode) cannot 3930 * be modified by execution of the test, and so are passed unchanged 3931 * from the caller to the target or fallback as appropriate. 3932 * @param test method handle used for test, must return boolean 3933 * @param target method handle to call if test passes 3934 * @param fallback method handle to call if test fails 3935 * @return method handle which incorporates the specified if/then/else logic 3936 * @throws NullPointerException if any argument is null 3937 * @throws IllegalArgumentException if {@code test} does not return boolean, 3938 * or if all three method types do not match (with the return 3939 * type of {@code test} changed to match that of the target). 3940 */ 3941 public static 3942 MethodHandle guardWithTest(MethodHandle test, 3943 MethodHandle target, 3944 MethodHandle fallback) { 3945 MethodType gtype = test.type(); 3946 MethodType ttype = target.type(); 3947 MethodType ftype = fallback.type(); 3948 if (!ttype.equals(ftype)) 3949 throw misMatchedTypes("target and fallback types", ttype, ftype); 3950 if (gtype.returnType() != boolean.class) 3951 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 3952 List<Class<?>> targs = ttype.parameterList(); 3953 test = dropArgumentsToMatch(test, 0, targs, 0, true); 3954 if (test == null) { 3955 throw misMatchedTypes("target and test types", ttype, gtype); 3956 } 3957 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 3958 } 3959 3960 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 3961 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 3962 } 3963 3964 /** 3965 * Makes a method handle which adapts a target method handle, 3966 * by running it inside an exception handler. 3967 * If the target returns normally, the adapter returns that value. 3968 * If an exception matching the specified type is thrown, the fallback 3969 * handle is called instead on the exception, plus the original arguments. 3970 * <p> 3971 * The target and handler must have the same corresponding 3972 * argument and return types, except that handler may omit trailing arguments 3973 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 3974 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 3975 * <p> 3976 * Here is pseudocode for the resulting adapter. In the code, {@code T} 3977 * represents the return type of the {@code target} and {@code handler}, 3978 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 3979 * the types and values of arguments to the resulting handle consumed by 3980 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 3981 * resulting handle discarded by {@code handler}. 3982 * <blockquote><pre>{@code 3983 * T target(A..., B...); 3984 * T handler(ExType, A...); 3985 * T adapter(A... a, B... b) { 3986 * try { 3987 * return target(a..., b...); 3988 * } catch (ExType ex) { 3989 * return handler(ex, a...); 3990 * } 3991 * } 3992 * }</pre></blockquote> 3993 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 3994 * be modified by execution of the target, and so are passed unchanged 3995 * from the caller to the handler, if the handler is invoked. 3996 * <p> 3997 * The target and handler must return the same type, even if the handler 3998 * always throws. (This might happen, for instance, because the handler 3999 * is simulating a {@code finally} clause). 4000 * To create such a throwing handler, compose the handler creation logic 4001 * with {@link #throwException throwException}, 4002 * in order to create a method handle of the correct return type. 4003 * @param target method handle to call 4004 * @param exType the type of exception which the handler will catch 4005 * @param handler method handle to call if a matching exception is thrown 4006 * @return method handle which incorporates the specified try/catch logic 4007 * @throws NullPointerException if any argument is null 4008 * @throws IllegalArgumentException if {@code handler} does not accept 4009 * the given exception type, or if the method handle types do 4010 * not match in their return types and their 4011 * corresponding parameters 4012 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 4013 */ 4014 public static 4015 MethodHandle catchException(MethodHandle target, 4016 Class<? extends Throwable> exType, 4017 MethodHandle handler) { 4018 MethodType ttype = target.type(); 4019 MethodType htype = handler.type(); 4020 if (!Throwable.class.isAssignableFrom(exType)) 4021 throw new ClassCastException(exType.getName()); 4022 if (htype.parameterCount() < 1 || 4023 !htype.parameterType(0).isAssignableFrom(exType)) 4024 throw newIllegalArgumentException("handler does not accept exception type "+exType); 4025 if (htype.returnType() != ttype.returnType()) 4026 throw misMatchedTypes("target and handler return types", ttype, htype); 4027 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); 4028 if (handler == null) { 4029 throw misMatchedTypes("target and handler types", ttype, htype); 4030 } 4031 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 4032 } 4033 4034 /** 4035 * Produces a method handle which will throw exceptions of the given {@code exType}. 4036 * The method handle will accept a single argument of {@code exType}, 4037 * and immediately throw it as an exception. 4038 * The method type will nominally specify a return of {@code returnType}. 4039 * The return type may be anything convenient: It doesn't matter to the 4040 * method handle's behavior, since it will never return normally. 4041 * @param returnType the return type of the desired method handle 4042 * @param exType the parameter type of the desired method handle 4043 * @return method handle which can throw the given exceptions 4044 * @throws NullPointerException if either argument is null 4045 */ 4046 public static 4047 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 4048 if (!Throwable.class.isAssignableFrom(exType)) 4049 throw new ClassCastException(exType.getName()); 4050 return MethodHandleImpl.throwException(methodType(returnType, exType)); 4051 } 4052 4053 /** 4054 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 4055 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 4056 * delivers the loop's result, which is the return value of the resulting handle. 4057 * <p> 4058 * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop 4059 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 4060 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 4061 * terms of method handles, each clause will determine four actions:<ul> 4062 * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local. 4063 * <li>When a clause executes, an update step for the iteration variable. 4064 * <li>When a clause executes, a predicate execution to test for loop exit. 4065 * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 4066 * </ul> 4067 * <p> 4068 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 4069 * this case. See below for a detailed description. 4070 * <p> 4071 * Each clause function, with the exception of clause initializers, is able to observe the entire loop state, 4072 * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop 4073 * parameters. Most clause functions will not need all of this information, but they will be formally connected as 4074 * if by {@link #dropArguments}. 4075 * <p> 4076 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 4077 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 4078 * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met 4079 * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means 4080 * that they must be identical, or else one list must be a proper prefix of the other. 4081 * <p> 4082 * <em>Step 0: Determine clause structure.</em><ol type="a"> 4083 * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element. 4084 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 4085 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 4086 * four. Padding takes place by appending elements to the array. 4087 * <li>Clauses with all {@code null}s are disregarded. 4088 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 4089 * </ol> 4090 * <p> 4091 * <em>Step 1A: Determine iteration variables.</em><ol type="a"> 4092 * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type. 4093 * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else 4094 * use the common return type (they must be identical). 4095 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 4096 * <li>This list of types is called the "common prefix". 4097 * </ol> 4098 * <p> 4099 * <em>Step 1B: Determine loop parameters.</em><ul> 4100 * <li><b>If at least one init function is given,</b><ol type="a"> 4101 * <li>Examine init function parameter lists. 4102 * <li>Omitted init functions are deemed to have {@code null} parameter lists. 4103 * <li>All init function parameter lists must be effectively identical. 4104 * <li>The longest parameter list (which is necessarily unique) is called the "common suffix". 4105 * </ol> 4106 * <li><b>If no init function is given,</b><ol type="a"> 4107 * <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix". 4108 * <li>The longest of these suffixes is taken as the "common suffix". 4109 * </ol></ul> 4110 * <p> 4111 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 4112 * <li>Examine fini function return types, disregarding omitted fini functions. 4113 * <li>If there are no fini functions, use {@code void} as the loop return type. 4114 * <li>Otherwise, use the common return type of the fini functions; they must all be identical. 4115 * </ol> 4116 * <p> 4117 * <em>Step 1D: Check other types.</em><ol type="a"> 4118 * <li>There must be at least one non-omitted pred function. 4119 * <li>Every non-omitted pred function must have a {@code boolean} return type. 4120 * </ol> 4121 * <p> 4122 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 4123 * <li>The parameter list for the resulting loop handle will be the "common suffix". 4124 * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter 4125 * lists are already effectively identical to the common suffix.) 4126 * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix 4127 * followed by the common suffix, called the "common parameter sequence". 4128 * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter 4129 * sequence. 4130 * </ol> 4131 * <p> 4132 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 4133 * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate 4134 * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a 4135 * function which does nothing and returns {@code void}; it can be obtained from another constant function by 4136 * {@linkplain MethodHandle#asType type conversion}.) 4137 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 4138 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 4139 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 4140 * <li>If a pred function is omitted, the corresponding fini function must also be omitted. 4141 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 4142 * as this clause is concerned.) 4143 * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the 4144 * loop return type. 4145 * </ol> 4146 * <p> 4147 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 4148 * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some 4149 * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by 4150 * {@linkplain #dropArguments dropping arguments}. 4151 * <li>At this point, every non-init function parameter list is effectively identical to the common parameter 4152 * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end 4153 * of the list by {@linkplain #dropArguments dropping arguments}. 4154 * </ol> 4155 * <p> 4156 * <em>Final observations.</em><ol type="a"> 4157 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 4158 * <li>All init functions have a common parameter type list, which the final loop handle will also have. 4159 * <li>All fini functions have a common return type, which the final loop handle will also have. 4160 * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of 4161 * (non-{@code void}) iteration variables followed by loop parameters. 4162 * <li>Each pair of init and step functions agrees in their return types. 4163 * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the 4164 * common prefix. 4165 * </ol> 4166 * <p> 4167 * <em>Loop execution.</em><ol type="a"> 4168 * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to 4169 * every clause function. These locals are loop invariant. 4170 * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values 4171 * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity 4172 * functions, as noted above). 4173 * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of 4174 * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order). 4175 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 4176 * returns {@code false}. 4177 * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The 4178 * updated value is immediately visible to all subsequent function calls. 4179 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 4180 * is returned from the loop as a whole. 4181 * </ol> 4182 * <p> 4183 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values 4184 * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the 4185 * result types of finalizers as well as of the resulting loop. 4186 * <blockquote><pre>{@code 4187 * V... init...(A...); 4188 * boolean pred...(V..., A...); 4189 * V... step...(V..., A...); 4190 * R fini...(V..., A...); 4191 * R loop(A... a) { 4192 * V... v... = init...(a...); 4193 * for (;;) { 4194 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 4195 * v = s(v..., a...); 4196 * if (!p(v..., a...)) { 4197 * return f(v..., a...); 4198 * } 4199 * } 4200 * } 4201 * } 4202 * }</pre></blockquote> 4203 * <p> 4204 * @apiNote Example: 4205 * <blockquote><pre>{@code 4206 * // iterative implementation of the factorial function as a loop handle 4207 * static int one(int k) { return 1; } 4208 * static int inc(int i, int acc, int k) { return i + 1; } 4209 * static int mult(int i, int acc, int k) { return i * acc; } 4210 * static boolean pred(int i, int acc, int k) { return i < k; } 4211 * static int fin(int i, int acc, int k) { return acc; } 4212 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4213 * // null initializer for counter, should initialize to 0 4214 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4215 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4216 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4217 * assertEquals(120, loop.invoke(5)); 4218 * }</pre></blockquote> 4219 * 4220 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 4221 * 4222 * @return a method handle embodying the looping behavior as defined by the arguments. 4223 * 4224 * @throws IllegalArgumentException in case any of the constraints described above is violated. 4225 * 4226 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 4227 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 4228 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 4229 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 4230 * @since 9 4231 */ 4232 public static MethodHandle loop(MethodHandle[]... clauses) { 4233 // Step 0: determine clause structure. 4234 checkLoop0(clauses); 4235 4236 List<MethodHandle> init = new ArrayList<>(); 4237 List<MethodHandle> step = new ArrayList<>(); 4238 List<MethodHandle> pred = new ArrayList<>(); 4239 List<MethodHandle> fini = new ArrayList<>(); 4240 4241 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 4242 init.add(clause[0]); // all clauses have at least length 1 4243 step.add(clause.length <= 1 ? null : clause[1]); 4244 pred.add(clause.length <= 2 ? null : clause[2]); 4245 fini.add(clause.length <= 3 ? null : clause[3]); 4246 }); 4247 4248 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 4249 final int nclauses = init.size(); 4250 4251 // Step 1A: determine iteration variables. 4252 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 4253 for (int i = 0; i < nclauses; ++i) { 4254 MethodHandle in = init.get(i); 4255 MethodHandle st = step.get(i); 4256 if (in == null && st == null) { 4257 iterationVariableTypes.add(void.class); 4258 } else if (in != null && st != null) { 4259 checkLoop1a(i, in, st); 4260 iterationVariableTypes.add(in.type().returnType()); 4261 } else { 4262 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 4263 } 4264 } 4265 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). 4266 collect(Collectors.toList()); 4267 4268 // Step 1B: determine loop parameters. 4269 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 4270 checkLoop1b(init, commonSuffix); 4271 4272 // Step 1C: determine loop return type. 4273 // Step 1D: check other types. 4274 final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type). 4275 map(MethodType::returnType).findFirst().orElse(void.class); 4276 checkLoop1cd(pred, fini, loopReturnType); 4277 4278 // Step 2: determine parameter lists. 4279 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 4280 commonParameterSequence.addAll(commonSuffix); 4281 checkLoop2(step, pred, fini, commonParameterSequence); 4282 4283 // Step 3: fill in omitted functions. 4284 for (int i = 0; i < nclauses; ++i) { 4285 Class<?> t = iterationVariableTypes.get(i); 4286 if (init.get(i) == null) { 4287 init.set(i, empty(methodType(t, commonSuffix))); 4288 } 4289 if (step.get(i) == null) { 4290 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 4291 } 4292 if (pred.get(i) == null) { 4293 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 4294 } 4295 if (fini.get(i) == null) { 4296 fini.set(i, empty(methodType(t, commonParameterSequence))); 4297 } 4298 } 4299 4300 // Step 4: fill in missing parameter types. 4301 List<MethodHandle> finit = fillParameterTypes(init, commonSuffix); 4302 List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence); 4303 List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence); 4304 List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence); 4305 4306 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 4307 allMatch(pl -> pl.equals(commonSuffix)); 4308 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 4309 allMatch(pl -> pl.equals(commonParameterSequence)); 4310 4311 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 4312 } 4313 4314 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 4315 return hs.stream().map(h -> { 4316 int pc = h.type().parameterCount(); 4317 int tpsize = targetParams.size(); 4318 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 4319 }).collect(Collectors.toList()); 4320 } 4321 4322 /** 4323 * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for 4324 * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 4325 * <p> 4326 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. 4327 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle 4328 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code 4329 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) 4330 * generic loop combinator}. 4331 * <p> 4332 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4333 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4334 * passed to the loop. 4335 * <blockquote><pre>{@code 4336 * V init(A); 4337 * boolean pred(V, A); 4338 * V body(V, A); 4339 * V whileLoop(A a) { 4340 * V v = init(a); 4341 * while (pred(v, a)) { 4342 * v = body(v, a); 4343 * } 4344 * return v; 4345 * } 4346 * }</pre></blockquote> 4347 * <p> 4348 * @apiNote Example: 4349 * <blockquote><pre>{@code 4350 * // implement the zip function for lists as a loop handle 4351 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 4352 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 4353 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 4354 * zip.add(a.next()); 4355 * zip.add(b.next()); 4356 * return zip; 4357 * } 4358 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 4359 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 4360 * List<String> a = Arrays.asList("a", "b", "c", "d"); 4361 * List<String> b = Arrays.asList("e", "f", "g", "h"); 4362 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 4363 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 4364 * }</pre></blockquote> 4365 * 4366 * <p> 4367 * @implSpec The implementation of this method is equivalent to: 4368 * <blockquote><pre>{@code 4369 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4370 * MethodHandle[] 4371 * checkExit = {null, null, pred, identity(init.type().returnType())}, 4372 * varBody = {init, body}; 4373 * return loop(checkExit, varBody); 4374 * } 4375 * }</pre></blockquote> 4376 * 4377 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's 4378 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type 4379 * {@code void}. 4380 * @param pred condition for the loop, which may not be {@code null}. 4381 * @param body body of the loop, which may not be {@code null}. 4382 * 4383 * @return the value of the loop variable as the loop terminates. 4384 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4385 * 4386 * @see MethodHandles#loop(MethodHandle[][]) 4387 * @since 9 4388 */ 4389 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4390 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : 4391 identity(init.type().returnType()); 4392 MethodHandle[] checkExit = {null, null, pred, fin}; 4393 MethodHandle[] varBody = {init, body}; 4394 return loop(checkExit, varBody); 4395 } 4396 4397 /** 4398 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper 4399 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4400 * <p> 4401 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. 4402 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle 4403 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code 4404 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) 4405 * generic loop combinator}. 4406 * <p> 4407 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4408 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4409 * passed to the loop. 4410 * <blockquote><pre>{@code 4411 * V init(A); 4412 * boolean pred(V, A); 4413 * V body(V, A); 4414 * V doWhileLoop(A a) { 4415 * V v = init(a); 4416 * do { 4417 * v = body(v, a); 4418 * } while (pred(v, a)); 4419 * return v; 4420 * } 4421 * }</pre></blockquote> 4422 * <p> 4423 * @apiNote Example: 4424 * <blockquote><pre>{@code 4425 * // int i = 0; while (i < limit) { ++i; } return i; => limit 4426 * static int zero(int limit) { return 0; } 4427 * static int step(int i, int limit) { return i + 1; } 4428 * static boolean pred(int i, int limit) { return i < limit; } 4429 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 4430 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 4431 * assertEquals(23, loop.invoke(23)); 4432 * }</pre></blockquote> 4433 * 4434 * <p> 4435 * @implSpec The implementation of this method is equivalent to: 4436 * <blockquote><pre>{@code 4437 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4438 * MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) }; 4439 * return loop(clause); 4440 * } 4441 * }</pre></blockquote> 4442 * 4443 * 4444 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's 4445 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type 4446 * {@code void}. 4447 * @param pred condition for the loop, which may not be {@code null}. 4448 * @param body body of the loop, which may not be {@code null}. 4449 * 4450 * @return the value of the loop variable as the loop terminates. 4451 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4452 * 4453 * @see MethodHandles#loop(MethodHandle[][]) 4454 * @since 9 4455 */ 4456 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4457 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : 4458 identity(init.type().returnType()); 4459 MethodHandle[] clause = {init, body, pred, fin}; 4460 return loop(clause); 4461 } 4462 4463 /** 4464 * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the 4465 * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must 4466 * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional 4467 * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop 4468 * combinator}. 4469 * <p> 4470 * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code 4471 * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code 4472 * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter, 4473 * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described 4474 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4475 * <p> 4476 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4477 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4478 * passed to the loop. 4479 * <blockquote><pre>{@code 4480 * int iterations(A); 4481 * V init(A); 4482 * V body(int, V, A); 4483 * V countedLoop(A a) { 4484 * int end = iterations(a); 4485 * V v = init(a); 4486 * for (int i = 0; i < end; ++i) { 4487 * v = body(i, v, a); 4488 * } 4489 * return v; 4490 * } 4491 * }</pre></blockquote> 4492 * <p> 4493 * @apiNote Example: 4494 * <blockquote><pre>{@code 4495 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 4496 * // => a variation on a well known theme 4497 * static String start(String arg) { return arg; } 4498 * static String step(int counter, String v, String arg) { return "na " + v; } 4499 * // assume MH_start and MH_step are handles to the two methods above 4500 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 4501 * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step); 4502 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 4503 * }</pre></blockquote> 4504 * 4505 * <p> 4506 * @implSpec The implementation of this method is equivalent to: 4507 * <blockquote><pre>{@code 4508 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4509 * return countedLoop(null, iterations, init, body); // null => constant zero 4510 * } 4511 * }</pre></blockquote> 4512 * 4513 * @param iterations a handle to return the number of iterations this loop should run. 4514 * @param init initializer for additional loop state. This determines the loop's result type. 4515 * Passing {@code null} or a {@code void} init function will make the loop's result type 4516 * {@code void}. 4517 * @param body the body of the loop, which must not be {@code null}. 4518 * It must accept an initial {@code int} parameter (for the counter), and then any 4519 * additional loop-local variable plus loop parameters. 4520 * 4521 * @return a method handle representing the loop. 4522 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4523 * 4524 * @since 9 4525 */ 4526 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4527 return countedLoop(null, iterations, init, body); 4528 } 4529 4530 /** 4531 * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be 4532 * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the 4533 * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code 4534 * body} function in each iteration; it has to accept an initial {@code int} parameter 4535 * for that. The result of the loop execution is the final value of the additional local state 4536 * obtained by running {@code init}. 4537 * This is a 4538 * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4539 * <p> 4540 * The constraints for the {@code init} and {@code body} handles are the same as for {@link 4541 * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles 4542 * must return an {@code int} and accept the same parameters as {@code init}. 4543 * <p> 4544 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4545 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4546 * passed to the loop. 4547 * <blockquote><pre>{@code 4548 * int start(A); 4549 * int end(A); 4550 * V init(A); 4551 * V body(int, V, A); 4552 * V countedLoop(A a) { 4553 * int s = start(a); 4554 * int e = end(a); 4555 * V v = init(a); 4556 * for (int i = s; i < e; ++i) { 4557 * v = body(i, v, a); 4558 * } 4559 * return v; 4560 * } 4561 * }</pre></blockquote> 4562 * 4563 * <p> 4564 * @implSpec The implementation of this method is equivalent to: 4565 * <blockquote><pre>{@code 4566 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4567 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 4568 * // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int, 4569 * // assume MH_decrement is a handle to x-1 of type int 4570 * MethodHandle[] 4571 * indexVar = {start, MH_increment}, // i = start; i = i+1 4572 * loopLimit = {end, null, MH_lessThan, returnVar }, // i<end 4573 * bodyClause = {init, 4574 * filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v) 4575 * return loop(indexVar, loopLimit, bodyClause); 4576 * } 4577 * }</pre></blockquote> 4578 * 4579 * @param start a handle to return the start value of the loop counter. 4580 * If it is {@code null}, a constant zero is assumed. 4581 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}). 4582 * @param init initializer for additional loop state. This determines the loop's result type. 4583 * Passing {@code null} or a {@code void} init function will make the loop's result type 4584 * {@code void}. 4585 * @param body the body of the loop, which must not be {@code null}. 4586 * It must accept an initial {@code int} parameter (for the counter), and then any 4587 * additional loop-local variable plus loop parameters. 4588 * 4589 * @return a method handle representing the loop. 4590 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4591 * 4592 * @since 9 4593 */ 4594 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4595 Class<?> resultType; 4596 MethodHandle actualInit; 4597 if (init == null) { 4598 resultType = body == null ? void.class : body.type().returnType(); 4599 actualInit = empty(methodType(resultType)); 4600 } else { 4601 resultType = init.type().returnType(); 4602 actualInit = init; 4603 } 4604 MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType); 4605 MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body; 4606 MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class); 4607 MethodHandle actualEnd = end == null ? constant(int.class, 0) : end; 4608 MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)}; 4609 MethodHandle[] loopLimit = {actualEnd, null, 4610 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar}; 4611 MethodHandle[] bodyClause = {actualInit, 4612 filterArgument(dropArguments(actualBody, 1, int.class), 0, 4613 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter))}; 4614 return loop(indexVar, loopLimit, bodyClause); 4615 } 4616 4617 /** 4618 * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}. 4619 * The iterator will be produced by the evaluation of the {@code iterator} handle. 4620 * This handle must have {@link java.util.Iterator} as its return type. 4621 * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead, 4622 * and will be applied to a leading argument of the loop handle. 4623 * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter. 4624 * The result of the loop execution is the final value of the additional local state 4625 * obtained by running {@code init}. 4626 * <p> 4627 * This is a convenience wrapper for the 4628 * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body} 4629 * handle follow directly from those described for the latter. 4630 * <p> 4631 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4632 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 4633 * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop. 4634 * <blockquote><pre>{@code 4635 * Iterator<T> iterator(A); // defaults to Iterable::iterator 4636 * V init(A); 4637 * V body(T,V,A); 4638 * V iteratedLoop(A a) { 4639 * Iterator<T> it = iterator(a); 4640 * V v = init(a); 4641 * for (T t : it) { 4642 * v = body(t, v, a); 4643 * } 4644 * return v; 4645 * } 4646 * }</pre></blockquote> 4647 * <p> 4648 * The type {@code T} may be either a primitive or reference. 4649 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type 4650 * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} 4651 * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method. 4652 * Therefore, if an iterator of the wrong type appears as the loop is executed, 4653 * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}. 4654 * <p> 4655 * @apiNote Example: 4656 * <blockquote><pre>{@code 4657 * // reverse a list 4658 * static List<String> reverseStep(String e, List<String> r, List<String> l) { 4659 * r.add(0, e); 4660 * return r; 4661 * } 4662 * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); } 4663 * // assume MH_reverseStep, MH_newArrayList are handles to the above methods 4664 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 4665 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 4666 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 4667 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 4668 * }</pre></blockquote> 4669 * <p> 4670 * @implSpec The implementation of this method is equivalent to (excluding error handling): 4671 * <blockquote><pre>{@code 4672 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 4673 * // assume MH_next and MH_hasNext are handles to methods of Iterator 4674 * Class<?> itype = iterator.type().returnType(); 4675 * Class<?> ttype = body.type().parameterType(0); 4676 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype); 4677 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 4678 * MethodHandle[] 4679 * iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext) 4680 * bodyClause = {init, filterArgument(body, 0, nextVal)}; // v = body(t, v, a); 4681 * return loop(iterVar, bodyClause); 4682 * } 4683 * }</pre></blockquote> 4684 * 4685 * @param iterator a handle to return the iterator to start the loop. 4686 * The handle must have {@link java.util.Iterator} as its return type. 4687 * Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first 4688 * incoming value. 4689 * @param init initializer for additional loop state. This determines the loop's result type. 4690 * Passing {@code null} or a {@code void} init function will make the loop's result type 4691 * {@code void}. 4692 * @param body the body of the loop, which must not be {@code null}. 4693 * It must accept an initial {@code T} parameter (for the iterated values), and then any 4694 * additional loop-local variable plus loop parameters. 4695 * 4696 * @return a method handle embodying the iteration loop functionality. 4697 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4698 * 4699 * @since 9 4700 */ 4701 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 4702 checkIteratedLoop(iterator, body); 4703 Class<?> resultType = init == null ? 4704 body == null ? void.class : body.type().returnType() : 4705 init.type().returnType(); 4706 boolean voidResult = resultType == void.class; 4707 4708 MethodHandle initIterator; 4709 if (iterator == null) { 4710 MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 4711 initIterator = initit.asType(initit.type().changeParameterType(0, 4712 body.type().parameterType(voidResult ? 1 : 2))); 4713 } else { 4714 initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class)); 4715 } 4716 4717 Class<?> ttype = body.type().parameterType(0); 4718 4719 MethodHandle returnVar = 4720 dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class); 4721 MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 4722 MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype)); 4723 4724 MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred), 4725 returnVar}; 4726 MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)}; 4727 4728 return loop(iterVar, bodyClause); 4729 } 4730 4731 /** 4732 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 4733 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 4734 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 4735 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 4736 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 4737 * {@code try-finally} handle. 4738 * <p> 4739 * The {@code cleanup} handle will be passed one or two additional leading arguments. 4740 * The first is the exception thrown during the 4741 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 4742 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 4743 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 4744 * The second argument is not present if the {@code target} handle has a {@code void} return type. 4745 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 4746 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 4747 * <p> 4748 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 4749 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 4750 * two extra leading parameters:<ul> 4751 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 4752 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 4753 * the result from the execution of the {@code target} handle. 4754 * This parameter is not present if the {@code target} returns {@code void}. 4755 * </ul> 4756 * <p> 4757 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 4758 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 4759 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 4760 * the cleanup. 4761 * <blockquote><pre>{@code 4762 * V target(A..., B...); 4763 * V cleanup(Throwable, V, A...); 4764 * V adapter(A... a, B... b) { 4765 * V result = (zero value for V); 4766 * Throwable throwable = null; 4767 * try { 4768 * result = target(a..., b...); 4769 * } catch (Throwable t) { 4770 * throwable = t; 4771 * throw t; 4772 * } finally { 4773 * result = cleanup(throwable, result, a...); 4774 * } 4775 * return result; 4776 * } 4777 * }</pre></blockquote> 4778 * <p> 4779 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 4780 * be modified by execution of the target, and so are passed unchanged 4781 * from the caller to the cleanup, if it is invoked. 4782 * <p> 4783 * The target and cleanup must return the same type, even if the cleanup 4784 * always throws. 4785 * To create such a throwing cleanup, compose the cleanup logic 4786 * with {@link #throwException throwException}, 4787 * in order to create a method handle of the correct return type. 4788 * <p> 4789 * Note that {@code tryFinally} never converts exceptions into normal returns. 4790 * In rare cases where exceptions must be converted in that way, first wrap 4791 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 4792 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 4793 * 4794 * @param target the handle whose execution is to be wrapped in a {@code try} block. 4795 * @param cleanup the handle that is invoked in the finally block. 4796 * 4797 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 4798 * @throws NullPointerException if any argument is null 4799 * @throws IllegalArgumentException if {@code cleanup} does not accept 4800 * the required leading arguments, or if the method handle types do 4801 * not match in their return types and their 4802 * corresponding trailing parameters 4803 * 4804 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 4805 * @since 9 4806 */ 4807 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 4808 List<Class<?>> targetParamTypes = target.type().parameterList(); 4809 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); 4810 Class<?> rtype = target.type().returnType(); 4811 4812 checkTryFinally(target, cleanup); 4813 4814 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 4815 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 4816 // target parameter list. 4817 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); 4818 4819 return MethodHandleImpl.makeTryFinally(target, cleanup, rtype, targetParamTypes); 4820 } 4821 4822 /** 4823 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 4824 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 4825 * before the folded arguments. 4826 * <p> 4827 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 4828 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 4829 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 4830 * 0. 4831 * <p> 4832 * @apiNote Example: 4833 * <blockquote><pre>{@code 4834 import static java.lang.invoke.MethodHandles.*; 4835 import static java.lang.invoke.MethodType.*; 4836 ... 4837 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 4838 "println", methodType(void.class, String.class)) 4839 .bindTo(System.out); 4840 MethodHandle cat = lookup().findVirtual(String.class, 4841 "concat", methodType(String.class, String.class)); 4842 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 4843 MethodHandle catTrace = foldArguments(cat, 1, trace); 4844 // also prints "jum": 4845 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 4846 * }</pre></blockquote> 4847 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 4848 * represents the result type of the {@code target} and resulting adapter. 4849 * {@code V}/{@code v} represent the type and value of the parameter and argument 4850 * of {@code target} that precedes the folding position; {@code V} also is 4851 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 4852 * types and values of the {@code N} parameters and arguments at the folding 4853 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 4854 * and values of the {@code target} parameters and arguments that precede and 4855 * follow the folded parameters and arguments starting at {@code pos}, 4856 * respectively. 4857 * <blockquote><pre>{@code 4858 * // there are N arguments in A... 4859 * T target(Z..., V, A[N]..., B...); 4860 * V combiner(A...); 4861 * T adapter(Z... z, A... a, B... b) { 4862 * V v = combiner(a...); 4863 * return target(z..., v, a..., b...); 4864 * } 4865 * // and if the combiner has a void return: 4866 * T target2(Z..., A[N]..., B...); 4867 * void combiner2(A...); 4868 * T adapter2(Z... z, A... a, B... b) { 4869 * combiner2(a...); 4870 * return target2(z..., a..., b...); 4871 * } 4872 * }</pre></blockquote> 4873 * <p> 4874 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4875 * variable-arity method handle}, even if the original target method handle was. 4876 * 4877 * @param target the method handle to invoke after arguments are combined 4878 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 4879 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 4880 * @param combiner method handle to call initially on the incoming arguments 4881 * @return method handle which incorporates the specified argument folding logic 4882 * @throws NullPointerException if either argument is null 4883 * @throws IllegalArgumentException if {@code combiner}'s return type 4884 * is non-void and not the same as the argument type at position {@code pos} of 4885 * the target signature, or if the {@code N} argument types at position {@code pos} 4886 * of the target signature 4887 * (skipping one matching the {@code combiner}'s return type) 4888 * are not identical with the argument types of {@code combiner} 4889 * 4890 * @see #foldArguments(MethodHandle, MethodHandle) 4891 * @since 9 4892 */ 4893 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 4894 MethodType targetType = target.type(); 4895 MethodType combinerType = combiner.type(); 4896 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 4897 BoundMethodHandle result = target.rebind(); 4898 boolean dropResult = rtype == void.class; 4899 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 4900 MethodType newType = targetType; 4901 if (!dropResult) { 4902 newType = newType.dropParameterTypes(pos, pos + 1); 4903 } 4904 result = result.copyWithExtendL(newType, lform, combiner); 4905 return result; 4906 } 4907 4908 4909 private static void checkLoop0(MethodHandle[][] clauses) { 4910 if (clauses == null || clauses.length == 0) { 4911 throw newIllegalArgumentException("null or no clauses passed"); 4912 } 4913 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 4914 throw newIllegalArgumentException("null clauses are not allowed"); 4915 } 4916 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 4917 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 4918 } 4919 } 4920 4921 private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) { 4922 if (in.type().returnType() != st.type().returnType()) { 4923 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 4924 st.type().returnType()); 4925 } 4926 } 4927 4928 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 4929 final List<Class<?>> empty = List.of(); 4930 final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList()); 4931 if (nonNullInits.isEmpty()) { 4932 final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull). 4933 // take only those that can contribute to a common suffix because they are longer than the prefix 4934 map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList). 4935 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 4936 return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size()); 4937 } else { 4938 return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList). 4939 reduce((p, q) -> p.size() >= q.size() ? p : q).get(); 4940 } 4941 } 4942 4943 private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 4944 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList). 4945 anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) { 4946 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 4947 " (common suffix: " + commonSuffix + ")"); 4948 } 4949 } 4950 4951 private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 4952 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4953 anyMatch(t -> t != loopReturnType)) { 4954 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 4955 loopReturnType + ")"); 4956 } 4957 4958 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { 4959 throw newIllegalArgumentException("no predicate found", pred); 4960 } 4961 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4962 anyMatch(t -> t != boolean.class)) { 4963 throw newIllegalArgumentException("predicates must have boolean return type", pred); 4964 } 4965 } 4966 4967 private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 4968 final int cpSize = commonParameterSequence.size(); 4969 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 4970 map(MethodType::parameterList). 4971 anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) { 4972 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 4973 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 4974 } 4975 } 4976 4977 private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) { 4978 if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) { 4979 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 4980 } 4981 if (null == body) { 4982 throw newIllegalArgumentException("iterated loop body must not be null"); 4983 } 4984 } 4985 4986 private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) { 4987 Class<?> rtype = target.type().returnType(); 4988 if (rtype != cleanup.type().returnType()) { 4989 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 4990 } 4991 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); 4992 if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) { 4993 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 4994 } 4995 if (rtype != void.class && cleanupParamTypes.get(1) != rtype) { 4996 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 4997 } 4998 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 4999 // target parameter list. 5000 int cleanupArgIndex = rtype == void.class ? 1 : 2; 5001 List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size()); 5002 List<Class<?>> targetParamTypes = target.type().parameterList(); 5003 if (targetParamTypes.size() < cleanupArgSuffix.size() || 5004 !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) { 5005 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 5006 cleanup.type(), target.type()); 5007 } 5008 } 5009 5010 }