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