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