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