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