1 /* 2 * Copyright (c) 2008, 2013, 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 29 import java.util.*; 30 import sun.invoke.util.*; 31 import sun.misc.Unsafe; 32 33 import static java.lang.invoke.MethodHandleStatics.*; 34 35 /** 36 * A method handle is a typed, directly executable reference to an underlying method, 37 * constructor, field, or similar low-level operation, with optional 38 * transformations of arguments or return values. 39 * These transformations are quite general, and include such patterns as 40 * {@linkplain #asType conversion}, 41 * {@linkplain #bindTo insertion}, 42 * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion}, 43 * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}. 44 * 45 * <h1>Method handle contents</h1> 46 * Method handles are dynamically and strongly typed according to their parameter and return types. 47 * They are not distinguished by the name or the defining class of their underlying methods. 48 * A method handle must be invoked using a symbolic type descriptor which matches 49 * the method handle's own {@linkplain #type type descriptor}. 50 * <p> 51 * Every method handle reports its type descriptor via the {@link #type type} accessor. 52 * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object, 53 * whose structure is a series of classes, one of which is 54 * the return type of the method (or {@code void.class} if none). 55 * <p> 56 * A method handle's type controls the types of invocations it accepts, 57 * and the kinds of transformations that apply to it. 58 * <p> 59 * A method handle contains a pair of special invoker methods 60 * called {@link #invokeExact invokeExact} and {@link #invoke invoke}. 61 * Both invoker methods provide direct access to the method handle's 62 * underlying method, constructor, field, or other operation, 63 * as modified by transformations of arguments and return values. 64 * Both invokers accept calls which exactly match the method handle's own type. 65 * The plain, inexact invoker also accepts a range of other call types. 66 * <p> 67 * Method handles are immutable and have no visible state. 68 * Of course, they can be bound to underlying methods or data which exhibit state. 69 * With respect to the Java Memory Model, any method handle will behave 70 * as if all of its (internal) fields are final variables. This means that any method 71 * handle made visible to the application will always be fully formed. 72 * This is true even if the method handle is published through a shared 73 * variable in a data race. 74 * <p> 75 * Method handles cannot be subclassed by the user. 76 * Implementations may (or may not) create internal subclasses of {@code MethodHandle} 77 * which may be visible via the {@link java.lang.Object#getClass Object.getClass} 78 * operation. The programmer should not draw conclusions about a method handle 79 * from its specific class, as the method handle class hierarchy (if any) 80 * may change from time to time or across implementations from different vendors. 81 * 82 * <h1>Method handle compilation</h1> 83 * A Java method call expression naming {@code invokeExact} or {@code invoke} 84 * can invoke a method handle from Java source code. 85 * From the viewpoint of source code, these methods can take any arguments 86 * and their result can be cast to any return type. 87 * Formally this is accomplished by giving the invoker methods 88 * {@code Object} return types and variable arity {@code Object} arguments, 89 * but they have an additional quality called <em>signature polymorphism</em> 90 * which connects this freedom of invocation directly to the JVM execution stack. 91 * <p> 92 * As is usual with virtual methods, source-level calls to {@code invokeExact} 93 * and {@code invoke} compile to an {@code invokevirtual} instruction. 94 * More unusually, the compiler must record the actual argument types, 95 * and may not perform method invocation conversions on the arguments. 96 * Instead, it must push them on the stack according to their own unconverted types. 97 * The method handle object itself is pushed on the stack before the arguments. 98 * The compiler then calls the method handle with a symbolic type descriptor which 99 * describes the argument and return types. 100 * <p> 101 * To issue a complete symbolic type descriptor, the compiler must also determine 102 * the return type. This is based on a cast on the method invocation expression, 103 * if there is one, or else {@code Object} if the invocation is an expression 104 * or else {@code void} if the invocation is a statement. 105 * The cast may be to a primitive type (but not {@code void}). 106 * <p> 107 * As a corner case, an uncasted {@code null} argument is given 108 * a symbolic type descriptor of {@code java.lang.Void}. 109 * The ambiguity with the type {@code Void} is harmless, since there are no references of type 110 * {@code Void} except the null reference. 111 * 112 * <h1>Method handle invocation</h1> 113 * The first time a {@code invokevirtual} instruction is executed 114 * it is linked, by symbolically resolving the names in the instruction 115 * and verifying that the method call is statically legal. 116 * This is true of calls to {@code invokeExact} and {@code invoke}. 117 * In this case, the symbolic type descriptor emitted by the compiler is checked for 118 * correct syntax and names it contains are resolved. 119 * Thus, an {@code invokevirtual} instruction which invokes 120 * a method handle will always link, as long 121 * as the symbolic type descriptor is syntactically well-formed 122 * and the types exist. 123 * <p> 124 * When the {@code invokevirtual} is executed after linking, 125 * the receiving method handle's type is first checked by the JVM 126 * to ensure that it matches the symbolic type descriptor. 127 * If the type match fails, it means that the method which the 128 * caller is invoking is not present on the individual 129 * method handle being invoked. 130 * <p> 131 * In the case of {@code invokeExact}, the type descriptor of the invocation 132 * (after resolving symbolic type names) must exactly match the method type 133 * of the receiving method handle. 134 * In the case of plain, inexact {@code invoke}, the resolved type descriptor 135 * must be a valid argument to the receiver's {@link #asType asType} method. 136 * Thus, plain {@code invoke} is more permissive than {@code invokeExact}. 137 * <p> 138 * After type matching, a call to {@code invokeExact} directly 139 * and immediately invoke the method handle's underlying method 140 * (or other behavior, as the case may be). 141 * <p> 142 * A call to plain {@code invoke} works the same as a call to 143 * {@code invokeExact}, if the symbolic type descriptor specified by the caller 144 * exactly matches the method handle's own type. 145 * If there is a type mismatch, {@code invoke} attempts 146 * to adjust the type of the receiving method handle, 147 * as if by a call to {@link #asType asType}, 148 * to obtain an exactly invokable method handle {@code M2}. 149 * This allows a more powerful negotiation of method type 150 * between caller and callee. 151 * <p> 152 * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable, 153 * and implementations are therefore not required to materialize it.) 154 * 155 * <h1>Invocation checking</h1> 156 * In typical programs, method handle type matching will usually succeed. 157 * But if a match fails, the JVM will throw a {@link WrongMethodTypeException}, 158 * either directly (in the case of {@code invokeExact}) or indirectly as if 159 * by a failed call to {@code asType} (in the case of {@code invoke}). 160 * <p> 161 * Thus, a method type mismatch which might show up as a linkage error 162 * in a statically typed program can show up as 163 * a dynamic {@code WrongMethodTypeException} 164 * in a program which uses method handles. 165 * <p> 166 * Because method types contain "live" {@code Class} objects, 167 * method type matching takes into account both types names and class loaders. 168 * Thus, even if a method handle {@code M} is created in one 169 * class loader {@code L1} and used in another {@code L2}, 170 * method handle calls are type-safe, because the caller's symbolic type 171 * descriptor, as resolved in {@code L2}, 172 * is matched against the original callee method's symbolic type descriptor, 173 * as resolved in {@code L1}. 174 * The resolution in {@code L1} happens when {@code M} is created 175 * and its type is assigned, while the resolution in {@code L2} happens 176 * when the {@code invokevirtual} instruction is linked. 177 * <p> 178 * Apart from the checking of type descriptors, 179 * a method handle's capability to call its underlying method is unrestricted. 180 * If a method handle is formed on a non-public method by a class 181 * that has access to that method, the resulting handle can be used 182 * in any place by any caller who receives a reference to it. 183 * <p> 184 * Unlike with the Core Reflection API, where access is checked every time 185 * a reflective method is invoked, 186 * method handle access checking is performed 187 * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>. 188 * In the case of {@code ldc} (see below), access checking is performed as part of linking 189 * the constant pool entry underlying the constant method handle. 190 * <p> 191 * Thus, handles to non-public methods, or to methods in non-public classes, 192 * should generally be kept secret. 193 * They should not be passed to untrusted code unless their use from 194 * the untrusted code would be harmless. 195 * 196 * <h1>Method handle creation</h1> 197 * Java code can create a method handle that directly accesses 198 * any method, constructor, or field that is accessible to that code. 199 * This is done via a reflective, capability-based API called 200 * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup} 201 * For example, a static method handle can be obtained 202 * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}. 203 * There are also conversion methods from Core Reflection API objects, 204 * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}. 205 * <p> 206 * Like classes and strings, method handles that correspond to accessible 207 * fields, methods, and constructors can also be represented directly 208 * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes. 209 * A new type of constant pool entry, {@code CONSTANT_MethodHandle}, 210 * refers directly to an associated {@code CONSTANT_Methodref}, 211 * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref} 212 * constant pool entry. 213 * (For full details on method handle constants, 214 * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.) 215 * <p> 216 * Method handles produced by lookups or constant loads from methods or 217 * constructors with the variable arity modifier bit ({@code 0x0080}) 218 * have a corresponding variable arity, as if they were defined with 219 * the help of {@link #asVarargsCollector asVarargsCollector}. 220 * <p> 221 * A method reference may refer either to a static or non-static method. 222 * In the non-static case, the method handle type includes an explicit 223 * receiver argument, prepended before any other arguments. 224 * In the method handle's type, the initial receiver argument is typed 225 * according to the class under which the method was initially requested. 226 * (E.g., if a non-static method handle is obtained via {@code ldc}, 227 * the type of the receiver is the class named in the constant pool entry.) 228 * <p> 229 * Method handle constants are subject to the same link-time access checks 230 * their corresponding bytecode instructions, and the {@code ldc} instruction 231 * will throw corresponding linkage errors if the bytecode behaviors would 232 * throw such errors. 233 * <p> 234 * As a corollary of this, access to protected members is restricted 235 * to receivers only of the accessing class, or one of its subclasses, 236 * and the accessing class must in turn be a subclass (or package sibling) 237 * of the protected member's defining class. 238 * If a method reference refers to a protected non-static method or field 239 * of a class outside the current package, the receiver argument will 240 * be narrowed to the type of the accessing class. 241 * <p> 242 * When a method handle to a virtual method is invoked, the method is 243 * always looked up in the receiver (that is, the first argument). 244 * <p> 245 * A non-virtual method handle to a specific virtual method implementation 246 * can also be created. These do not perform virtual lookup based on 247 * receiver type. Such a method handle simulates the effect of 248 * an {@code invokespecial} instruction to the same method. 249 * 250 * <h1>Usage examples</h1> 251 * Here are some examples of usage: 252 * <blockquote><pre>{@code 253 Object x, y; String s; int i; 254 MethodType mt; MethodHandle mh; 255 MethodHandles.Lookup lookup = MethodHandles.lookup(); 256 // mt is (char,char)String 257 mt = MethodType.methodType(String.class, char.class, char.class); 258 mh = lookup.findVirtual(String.class, "replace", mt); 259 s = (String) mh.invokeExact("daddy",'d','n'); 260 // invokeExact(Ljava/lang/String;CC)Ljava/lang/String; 261 assertEquals(s, "nanny"); 262 // weakly typed invocation (using MHs.invoke) 263 s = (String) mh.invokeWithArguments("sappy", 'p', 'v'); 264 assertEquals(s, "savvy"); 265 // mt is (Object[])List 266 mt = MethodType.methodType(java.util.List.class, Object[].class); 267 mh = lookup.findStatic(java.util.Arrays.class, "asList", mt); 268 assert(mh.isVarargsCollector()); 269 x = mh.invoke("one", "two"); 270 // invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; 271 assertEquals(x, java.util.Arrays.asList("one","two")); 272 // mt is (Object,Object,Object)Object 273 mt = MethodType.genericMethodType(3); 274 mh = mh.asType(mt); 275 x = mh.invokeExact((Object)1, (Object)2, (Object)3); 276 // invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; 277 assertEquals(x, java.util.Arrays.asList(1,2,3)); 278 // mt is ()int 279 mt = MethodType.methodType(int.class); 280 mh = lookup.findVirtual(java.util.List.class, "size", mt); 281 i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3)); 282 // invokeExact(Ljava/util/List;)I 283 assert(i == 3); 284 mt = MethodType.methodType(void.class, String.class); 285 mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt); 286 mh.invokeExact(System.out, "Hello, world."); 287 // invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V 288 * }</pre></blockquote> 289 * Each of the above calls to {@code invokeExact} or plain {@code invoke} 290 * generates a single invokevirtual instruction with 291 * the symbolic type descriptor indicated in the following comment. 292 * In these examples, the helper method {@code assertEquals} is assumed to 293 * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals} 294 * on its arguments, and asserts that the result is true. 295 * 296 * <h1>Exceptions</h1> 297 * The methods {@code invokeExact} and {@code invoke} are declared 298 * to throw {@link java.lang.Throwable Throwable}, 299 * which is to say that there is no static restriction on what a method handle 300 * can throw. Since the JVM does not distinguish between checked 301 * and unchecked exceptions (other than by their class, of course), 302 * there is no particular effect on bytecode shape from ascribing 303 * checked exceptions to method handle invocations. But in Java source 304 * code, methods which perform method handle calls must either explicitly 305 * throw {@code Throwable}, or else must catch all 306 * throwables locally, rethrowing only those which are legal in the context, 307 * and wrapping ones which are illegal. 308 * 309 * <h1><a name="sigpoly"></a>Signature polymorphism</h1> 310 * The unusual compilation and linkage behavior of 311 * {@code invokeExact} and plain {@code invoke} 312 * is referenced by the term <em>signature polymorphism</em>. 313 * As defined in the Java Language Specification, 314 * a signature polymorphic method is one which can operate with 315 * any of a wide range of call signatures and return types. 316 * <p> 317 * In source code, a call to a signature polymorphic method will 318 * compile, regardless of the requested symbolic type descriptor. 319 * As usual, the Java compiler emits an {@code invokevirtual} 320 * instruction with the given symbolic type descriptor against the named method. 321 * The unusual part is that the symbolic type descriptor is derived from 322 * the actual argument and return types, not from the method declaration. 323 * <p> 324 * When the JVM processes bytecode containing signature polymorphic calls, 325 * it will successfully link any such call, regardless of its symbolic type descriptor. 326 * (In order to retain type safety, the JVM will guard such calls with suitable 327 * dynamic type checks, as described elsewhere.) 328 * <p> 329 * Bytecode generators, including the compiler back end, are required to emit 330 * untransformed symbolic type descriptors for these methods. 331 * Tools which determine symbolic linkage are required to accept such 332 * untransformed descriptors, without reporting linkage errors. 333 * 334 * <h1>Interoperation between method handles and the Core Reflection API</h1> 335 * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API, 336 * any class member represented by a Core Reflection API object 337 * can be converted to a behaviorally equivalent method handle. 338 * For example, a reflective {@link java.lang.reflect.Method Method} can 339 * be converted to a method handle using 340 * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}. 341 * The resulting method handles generally provide more direct and efficient 342 * access to the underlying class members. 343 * <p> 344 * As a special case, 345 * when the Core Reflection API is used to view the signature polymorphic 346 * methods {@code invokeExact} or plain {@code invoke} in this class, 347 * they appear as ordinary non-polymorphic methods. 348 * Their reflective appearance, as viewed by 349 * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod}, 350 * is unaffected by their special status in this API. 351 * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers} 352 * will report exactly those modifier bits required for any similarly 353 * declared method, including in this case {@code native} and {@code varargs} bits. 354 * <p> 355 * As with any reflected method, these methods (when reflected) may be 356 * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}. 357 * However, such reflective calls do not result in method handle invocations. 358 * Such a call, if passed the required argument 359 * (a single one, of type {@code Object[]}), will ignore the argument and 360 * will throw an {@code UnsupportedOperationException}. 361 * <p> 362 * Since {@code invokevirtual} instructions can natively 363 * invoke method handles under any symbolic type descriptor, this reflective view conflicts 364 * with the normal presentation of these methods via bytecodes. 365 * Thus, these two native methods, when reflectively viewed by 366 * {@code Class.getDeclaredMethod}, may be regarded as placeholders only. 367 * <p> 368 * In order to obtain an invoker method for a particular type descriptor, 369 * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker}, 370 * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}. 371 * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual} 372 * API is also able to return a method handle 373 * to call {@code invokeExact} or plain {@code invoke}, 374 * for any specified type descriptor . 375 * 376 * <h1>Interoperation between method handles and Java generics</h1> 377 * A method handle can be obtained on a method, constructor, or field 378 * which is declared with Java generic types. 379 * As with the Core Reflection API, the type of the method handle 380 * will constructed from the erasure of the source-level type. 381 * When a method handle is invoked, the types of its arguments 382 * or the return value cast type may be generic types or type instances. 383 * If this occurs, the compiler will replace those 384 * types by their erasures when it constructs the symbolic type descriptor 385 * for the {@code invokevirtual} instruction. 386 * <p> 387 * Method handles do not represent 388 * their function-like types in terms of Java parameterized (generic) types, 389 * because there are three mismatches between function-like types and parameterized 390 * Java types. 391 * <ul> 392 * <li>Method types range over all possible arities, 393 * from no arguments to up to the <a href="MethodHandle.html#maxarity">maximum number</a> of allowed arguments. 394 * Generics are not variadic, and so cannot represent this.</li> 395 * <li>Method types can specify arguments of primitive types, 396 * which Java generic types cannot range over.</li> 397 * <li>Higher order functions over method handles (combinators) are 398 * often generic across a wide range of function types, including 399 * those of multiple arities. It is impossible to represent such 400 * genericity with a Java type parameter.</li> 401 * </ul> 402 * 403 * <h1><a name="maxarity"></a>Arity limits</h1> 404 * The JVM imposes on all methods and constructors of any kind an absolute 405 * limit of 255 stacked arguments. This limit can appear more restrictive 406 * in certain cases: 407 * <ul> 408 * <li>A {@code long} or {@code double} argument counts (for purposes of arity limits) as two argument slots. 409 * <li>A non-static method consumes an extra argument for the object on which the method is called. 410 * <li>A constructor consumes an extra argument for the object which is being constructed. 411 * <li>Since a method handle’s {@code invoke} method (or other signature-polymorphic method) is non-virtual, 412 * it consumes an extra argument for the method handle itself, in addition to any non-virtual receiver object. 413 * </ul> 414 * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments. 415 * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it. 416 * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}. 417 * In particular, a method handle’s type must not have an arity of the exact maximum 255. 418 * 419 * @see MethodType 420 * @see MethodHandles 421 * @author John Rose, JSR 292 EG 422 */ 423 public abstract class MethodHandle { 424 static { MethodHandleImpl.initStatics(); } 425 426 /** 427 * Internal marker interface which distinguishes (to the Java compiler) 428 * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>. 429 */ 430 @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD}) 431 @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) 432 @interface PolymorphicSignature { } 433 434 private final MethodType type; 435 /*private*/ final LambdaForm form; 436 // form is not private so that invokers can easily fetch it 437 /*private*/ MethodHandle asTypeCache; 438 // asTypeCache is not private so that invokers can easily fetch it 439 440 /** 441 * Reports the type of this method handle. 442 * Every invocation of this method handle via {@code invokeExact} must exactly match this type. 443 * @return the method handle type 444 */ 445 public MethodType type() { 446 return type; 447 } 448 449 /** 450 * Package-private constructor for the method handle implementation hierarchy. 451 * Method handle inheritance will be contained completely within 452 * the {@code java.lang.invoke} package. 453 */ 454 // @param type type (permanently assigned) of the new method handle 455 /*non-public*/ MethodHandle(MethodType type, LambdaForm form) { 456 type.getClass(); // explicit NPE 457 form.getClass(); // explicit NPE 458 this.type = type; 459 this.form = form; 460 461 form.prepare(); // TO DO: Try to delay this step until just before invocation. 462 } 463 464 /** 465 * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match. 466 * The symbolic type descriptor at the call site of {@code invokeExact} must 467 * exactly match this method handle's {@link #type type}. 468 * No conversions are allowed on arguments or return values. 469 * <p> 470 * When this method is observed via the Core Reflection API, 471 * it will appear as a single native method, taking an object array and returning an object. 472 * If this native method is invoked directly via 473 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI, 474 * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}, 475 * it will throw an {@code UnsupportedOperationException}. 476 * @param args the signature-polymorphic parameter list, statically represented using varargs 477 * @return the signature-polymorphic result, statically represented using {@code Object} 478 * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor 479 * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call 480 */ 481 public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable; 482 483 /** 484 * Invokes the method handle, allowing any caller type descriptor, 485 * and optionally performing conversions on arguments and return values. 486 * <p> 487 * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type}, 488 * the call proceeds as if by {@link #invokeExact invokeExact}. 489 * <p> 490 * Otherwise, the call proceeds as if this method handle were first 491 * adjusted by calling {@link #asType asType} to adjust this method handle 492 * to the required type, and then the call proceeds as if by 493 * {@link #invokeExact invokeExact} on the adjusted method handle. 494 * <p> 495 * There is no guarantee that the {@code asType} call is actually made. 496 * If the JVM can predict the results of making the call, it may perform 497 * adaptations directly on the caller's arguments, 498 * and call the target method handle according to its own exact type. 499 * <p> 500 * The resolved type descriptor at the call site of {@code invoke} must 501 * be a valid argument to the receivers {@code asType} method. 502 * In particular, the caller must specify the same argument arity 503 * as the callee's type, 504 * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}. 505 * <p> 506 * When this method is observed via the Core Reflection API, 507 * it will appear as a single native method, taking an object array and returning an object. 508 * If this native method is invoked directly via 509 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI, 510 * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}, 511 * it will throw an {@code UnsupportedOperationException}. 512 * @param args the signature-polymorphic parameter list, statically represented using varargs 513 * @return the signature-polymorphic result, statically represented using {@code Object} 514 * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor 515 * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails 516 * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call 517 */ 518 public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable; 519 520 /** 521 * Private method for trusted invocation of a method handle respecting simplified signatures. 522 * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM. 523 * <p> 524 * The caller signature is restricted to the following basic types: 525 * Object, int, long, float, double, and void return. 526 * <p> 527 * The caller is responsible for maintaining type correctness by ensuring 528 * that the each outgoing argument value is a member of the range of the corresponding 529 * callee argument type. 530 * (The caller should therefore issue appropriate casts and integer narrowing 531 * operations on outgoing argument values.) 532 * The caller can assume that the incoming result value is part of the range 533 * of the callee's return type. 534 * @param args the signature-polymorphic parameter list, statically represented using varargs 535 * @return the signature-polymorphic result, statically represented using {@code Object} 536 */ 537 /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable; 538 539 /** 540 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}. 541 * The caller signature is restricted to basic types as with {@code invokeBasic}. 542 * The trailing (not leading) argument must be a MemberName. 543 * @param args the signature-polymorphic parameter list, statically represented using varargs 544 * @return the signature-polymorphic result, statically represented using {@code Object} 545 */ 546 /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable; 547 548 /** 549 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}. 550 * The caller signature is restricted to basic types as with {@code invokeBasic}. 551 * The trailing (not leading) argument must be a MemberName. 552 * @param args the signature-polymorphic parameter list, statically represented using varargs 553 * @return the signature-polymorphic result, statically represented using {@code Object} 554 */ 555 /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable; 556 557 /** 558 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}. 559 * The caller signature is restricted to basic types as with {@code invokeBasic}. 560 * The trailing (not leading) argument must be a MemberName. 561 * @param args the signature-polymorphic parameter list, statically represented using varargs 562 * @return the signature-polymorphic result, statically represented using {@code Object} 563 */ 564 /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable; 565 566 /** 567 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}. 568 * The caller signature is restricted to basic types as with {@code invokeBasic}. 569 * The trailing (not leading) argument must be a MemberName. 570 * @param args the signature-polymorphic parameter list, statically represented using varargs 571 * @return the signature-polymorphic result, statically represented using {@code Object} 572 */ 573 /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable; 574 575 /** 576 * Performs a variable arity invocation, passing the arguments in the given list 577 * to the method handle, as if via an inexact {@link #invoke invoke} from a call site 578 * which mentions only the type {@code Object}, and whose arity is the length 579 * of the argument list. 580 * <p> 581 * Specifically, execution proceeds as if by the following steps, 582 * although the methods are not guaranteed to be called if the JVM 583 * can predict their effects. 584 * <ul> 585 * <li>Determine the length of the argument array as {@code N}. 586 * For a null reference, {@code N=0}. </li> 587 * <li>Determine the general type {@code TN} of {@code N} arguments as 588 * as {@code TN=MethodType.genericMethodType(N)}.</li> 589 * <li>Force the original target method handle {@code MH0} to the 590 * required type, as {@code MH1 = MH0.asType(TN)}. </li> 591 * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li> 592 * <li>Invoke the type-adjusted method handle on the unpacked arguments: 593 * MH1.invokeExact(A0, ...). </li> 594 * <li>Take the return value as an {@code Object} reference. </li> 595 * </ul> 596 * <p> 597 * Because of the action of the {@code asType} step, the following argument 598 * conversions are applied as necessary: 599 * <ul> 600 * <li>reference casting 601 * <li>unboxing 602 * <li>widening primitive conversions 603 * </ul> 604 * <p> 605 * The result returned by the call is boxed if it is a primitive, 606 * or forced to null if the return type is void. 607 * <p> 608 * This call is equivalent to the following code: 609 * <blockquote><pre>{@code 610 * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0); 611 * Object result = invoker.invokeExact(this, arguments); 612 * }</pre></blockquote> 613 * <p> 614 * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke}, 615 * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI. 616 * It can therefore be used as a bridge between native or reflective code and method handles. 617 * 618 * @param arguments the arguments to pass to the target 619 * @return the result returned by the target 620 * @throws ClassCastException if an argument cannot be converted by reference casting 621 * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments 622 * @throws Throwable anything thrown by the target method invocation 623 * @see MethodHandles#spreadInvoker 624 */ 625 public Object invokeWithArguments(Object... arguments) throws Throwable { 626 int argc = arguments == null ? 0 : arguments.length; 627 @SuppressWarnings("LocalVariableHidesMemberVariable") 628 MethodType type = type(); 629 if (type.parameterCount() != argc || isVarargsCollector()) { 630 // simulate invoke 631 return asType(MethodType.genericMethodType(argc)).invokeWithArguments(arguments); 632 } 633 MethodHandle invoker = type.invokers().varargsInvoker(); 634 return invoker.invokeExact(this, arguments); 635 } 636 637 /** 638 * Performs a variable arity invocation, passing the arguments in the given array 639 * to the method handle, as if via an inexact {@link #invoke invoke} from a call site 640 * which mentions only the type {@code Object}, and whose arity is the length 641 * of the argument array. 642 * <p> 643 * This method is also equivalent to the following code: 644 * <blockquote><pre>{@code 645 * invokeWithArguments(arguments.toArray() 646 * }</pre></blockquote> 647 * 648 * @param arguments the arguments to pass to the target 649 * @return the result returned by the target 650 * @throws NullPointerException if {@code arguments} is a null reference 651 * @throws ClassCastException if an argument cannot be converted by reference casting 652 * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments 653 * @throws Throwable anything thrown by the target method invocation 654 */ 655 public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable { 656 return invokeWithArguments(arguments.toArray()); 657 } 658 659 /** 660 * Produces an adapter method handle which adapts the type of the 661 * current method handle to a new type. 662 * The resulting method handle is guaranteed to report a type 663 * which is equal to the desired new type. 664 * <p> 665 * If the original type and new type are equal, returns {@code this}. 666 * <p> 667 * The new method handle, when invoked, will perform the following 668 * steps: 669 * <ul> 670 * <li>Convert the incoming argument list to match the original 671 * method handle's argument list. 672 * <li>Invoke the original method handle on the converted argument list. 673 * <li>Convert any result returned by the original method handle 674 * to the return type of new method handle. 675 * </ul> 676 * <p> 677 * This method provides the crucial behavioral difference between 678 * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}. 679 * The two methods 680 * perform the same steps when the caller's type descriptor exactly m atches 681 * the callee's, but when the types differ, plain {@link #invoke invoke} 682 * also calls {@code asType} (or some internal equivalent) in order 683 * to match up the caller's and callee's types. 684 * <p> 685 * If the current method is a variable arity method handle 686 * argument list conversion may involve the conversion and collection 687 * of several arguments into an array, as 688 * {@linkplain #asVarargsCollector described elsewhere}. 689 * In every other case, all conversions are applied <em>pairwise</em>, 690 * which means that each argument or return value is converted to 691 * exactly one argument or return value (or no return value). 692 * The applied conversions are defined by consulting the 693 * the corresponding component types of the old and new 694 * method handle types. 695 * <p> 696 * Let <em>T0</em> and <em>T1</em> be corresponding new and old parameter types, 697 * or old and new return types. Specifically, for some valid index {@code i}, let 698 * <em>T0</em>{@code =newType.parameterType(i)} and <em>T1</em>{@code =this.type().parameterType(i)}. 699 * Or else, going the other way for return values, let 700 * <em>T0</em>{@code =this.type().returnType()} and <em>T1</em>{@code =newType.returnType()}. 701 * If the types are the same, the new method handle makes no change 702 * to the corresponding argument or return value (if any). 703 * Otherwise, one of the following conversions is applied 704 * if possible: 705 * <ul> 706 * <li>If <em>T0</em> and <em>T1</em> are references, then a cast to <em>T1</em> is applied. 707 * (The types do not need to be related in any particular way. 708 * This is because a dynamic value of null can convert to any reference type.) 709 * <li>If <em>T0</em> and <em>T1</em> are primitives, then a Java method invocation 710 * conversion (JLS 5.3) is applied, if one exists. 711 * (Specifically, <em>T0</em> must convert to <em>T1</em> by a widening primitive conversion.) 712 * <li>If <em>T0</em> is a primitive and <em>T1</em> a reference, 713 * a Java casting conversion (JLS 5.5) is applied if one exists. 714 * (Specifically, the value is boxed from <em>T0</em> to its wrapper class, 715 * which is then widened as needed to <em>T1</em>.) 716 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 717 * conversion will be applied at runtime, possibly followed 718 * by a Java method invocation conversion (JLS 5.3) 719 * on the primitive value. (These are the primitive widening conversions.) 720 * <em>T0</em> must be a wrapper class or a supertype of one. 721 * (In the case where <em>T0</em> is Object, these are the conversions 722 * allowed by {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.) 723 * The unboxing conversion must have a possibility of success, which means that 724 * if <em>T0</em> is not itself a wrapper class, there must exist at least one 725 * wrapper class <em>TW</em> which is a subtype of <em>T0</em> and whose unboxed 726 * primitive value can be widened to <em>T1</em>. 727 * <li>If the return type <em>T1</em> is marked as void, any returned value is discarded 728 * <li>If the return type <em>T0</em> is void and <em>T1</em> a reference, a null value is introduced. 729 * <li>If the return type <em>T0</em> is void and <em>T1</em> a primitive, 730 * a zero value is introduced. 731 * </ul> 732 * (<em>Note:</em> Both <em>T0</em> and <em>T1</em> may be regarded as static types, 733 * because neither corresponds specifically to the <em>dynamic type</em> of any 734 * actual argument or return value.) 735 * <p> 736 * The method handle conversion cannot be made if any one of the required 737 * pairwise conversions cannot be made. 738 * <p> 739 * At runtime, the conversions applied to reference arguments 740 * or return values may require additional runtime checks which can fail. 741 * An unboxing operation may fail because the original reference is null, 742 * causing a {@link java.lang.NullPointerException NullPointerException}. 743 * An unboxing operation or a reference cast may also fail on a reference 744 * to an object of the wrong type, 745 * causing a {@link java.lang.ClassCastException ClassCastException}. 746 * Although an unboxing operation may accept several kinds of wrappers, 747 * if none are available, a {@code ClassCastException} will be thrown. 748 * 749 * @param newType the expected type of the new method handle 750 * @return a method handle which delegates to {@code this} after performing 751 * any necessary argument conversions, and arranges for any 752 * necessary return value conversions 753 * @throws NullPointerException if {@code newType} is a null reference 754 * @throws WrongMethodTypeException if the conversion cannot be made 755 * @see MethodHandles#explicitCastArguments 756 */ 757 public MethodHandle asType(MethodType newType) { 758 // Fast path alternative to a heavyweight {@code asType} call. 759 // Return 'this' if the conversion will be a no-op. 760 if (newType == type) { 761 return this; 762 } 763 // Return 'this.asTypeCache' if the conversion is already memoized. 764 MethodHandle atc = asTypeCache; 765 if (atc != null && newType == atc.type) { 766 return atc; 767 } 768 return asTypeUncached(newType); 769 } 770 771 /** Override this to change asType behavior. */ 772 /*non-public*/ MethodHandle asTypeUncached(MethodType newType) { 773 if (!type.isConvertibleTo(newType)) 774 throw new WrongMethodTypeException("cannot convert "+this+" to "+newType); 775 return asTypeCache = convertArguments(newType); 776 } 777 778 /** 779 * Makes an <em>array-spreading</em> method handle, which accepts a trailing array argument 780 * and spreads its elements as positional arguments. 781 * The new method handle adapts, as its <i>target</i>, 782 * the current method handle. The type of the adapter will be 783 * the same as the type of the target, except that the final 784 * {@code arrayLength} parameters of the target's type are replaced 785 * by a single array parameter of type {@code arrayType}. 786 * <p> 787 * If the array element type differs from any of the corresponding 788 * argument types on the original target, 789 * the original target is adapted to take the array elements directly, 790 * as if by a call to {@link #asType asType}. 791 * <p> 792 * When called, the adapter replaces a trailing array argument 793 * by the array's elements, each as its own argument to the target. 794 * (The order of the arguments is preserved.) 795 * They are converted pairwise by casting and/or unboxing 796 * to the types of the trailing parameters of the target. 797 * Finally the target is called. 798 * What the target eventually returns is returned unchanged by the adapter. 799 * <p> 800 * Before calling the target, the adapter verifies that the array 801 * contains exactly enough elements to provide a correct argument count 802 * to the target method handle. 803 * (The array may also be null when zero elements are required.) 804 * <p> 805 * If, when the adapter is called, the supplied array argument does 806 * not have the correct number of elements, the adapter will throw 807 * an {@link IllegalArgumentException} instead of invoking the target. 808 * <p> 809 * Here are some simple examples of array-spreading method handles: 810 * <blockquote><pre>{@code 811 MethodHandle equals = publicLookup() 812 .findVirtual(String.class, "equals", methodType(boolean.class, Object.class)); 813 assert( (boolean) equals.invokeExact("me", (Object)"me")); 814 assert(!(boolean) equals.invokeExact("me", (Object)"thee")); 815 // spread both arguments from a 2-array: 816 MethodHandle eq2 = equals.asSpreader(Object[].class, 2); 817 assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" })); 818 assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" })); 819 // try to spread from anything but a 2-array: 820 for (int n = 0; n <= 10; n++) { 821 Object[] badArityArgs = (n == 2 ? null : new Object[n]); 822 try { assert((boolean) eq2.invokeExact(badArityArgs) && false); } 823 catch (IllegalArgumentException ex) { } // OK 824 } 825 // spread both arguments from a String array: 826 MethodHandle eq2s = equals.asSpreader(String[].class, 2); 827 assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" })); 828 assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" })); 829 // spread second arguments from a 1-array: 830 MethodHandle eq1 = equals.asSpreader(Object[].class, 1); 831 assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" })); 832 assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" })); 833 // spread no arguments from a 0-array or null: 834 MethodHandle eq0 = equals.asSpreader(Object[].class, 0); 835 assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0])); 836 assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null)); 837 // asSpreader and asCollector are approximate inverses: 838 for (int n = 0; n <= 2; n++) { 839 for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) { 840 MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n); 841 assert( (boolean) equals2.invokeWithArguments("me", "me")); 842 assert(!(boolean) equals2.invokeWithArguments("me", "thee")); 843 } 844 } 845 MethodHandle caToString = publicLookup() 846 .findStatic(Arrays.class, "toString", methodType(String.class, char[].class)); 847 assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray())); 848 MethodHandle caString3 = caToString.asCollector(char[].class, 3); 849 assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C')); 850 MethodHandle caToString2 = caString3.asSpreader(char[].class, 2); 851 assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray())); 852 * }</pre></blockquote> 853 * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments 854 * @param arrayLength the number of arguments to spread from an incoming array argument 855 * @return a new method handle which spreads its final array argument, 856 * before calling the original method handle 857 * @throws NullPointerException if {@code arrayType} is a null reference 858 * @throws IllegalArgumentException if {@code arrayType} is not an array type, 859 * or if target does not have at least 860 * {@code arrayLength} parameter types, 861 * or if {@code arrayLength} is negative, 862 * or if the resulting method handle's type would have 863 * <a href="MethodHandle.html#maxarity">too many parameters</a> 864 * @throws WrongMethodTypeException if the implied {@code asType} call fails 865 * @see #asCollector 866 */ 867 public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) { 868 asSpreaderChecks(arrayType, arrayLength); 869 int spreadArgPos = type.parameterCount() - arrayLength; 870 return MethodHandleImpl.makeSpreadArguments(this, arrayType, spreadArgPos, arrayLength); 871 } 872 873 private void asSpreaderChecks(Class<?> arrayType, int arrayLength) { 874 spreadArrayChecks(arrayType, arrayLength); 875 int nargs = type().parameterCount(); 876 if (nargs < arrayLength || arrayLength < 0) 877 throw newIllegalArgumentException("bad spread array length"); 878 if (arrayType != Object[].class && arrayLength != 0) { 879 boolean sawProblem = false; 880 Class<?> arrayElement = arrayType.getComponentType(); 881 for (int i = nargs - arrayLength; i < nargs; i++) { 882 if (!MethodType.canConvert(arrayElement, type().parameterType(i))) { 883 sawProblem = true; 884 break; 885 } 886 } 887 if (sawProblem) { 888 ArrayList<Class<?>> ptypes = new ArrayList<>(type().parameterList()); 889 for (int i = nargs - arrayLength; i < nargs; i++) { 890 ptypes.set(i, arrayElement); 891 } 892 // elicit an error: 893 this.asType(MethodType.methodType(type().returnType(), ptypes)); 894 } 895 } 896 } 897 898 private void spreadArrayChecks(Class<?> arrayType, int arrayLength) { 899 Class<?> arrayElement = arrayType.getComponentType(); 900 if (arrayElement == null) 901 throw newIllegalArgumentException("not an array type", arrayType); 902 if ((arrayLength & 0x7F) != arrayLength) { 903 if ((arrayLength & 0xFF) != arrayLength) 904 throw newIllegalArgumentException("array length is not legal", arrayLength); 905 assert(arrayLength >= 128); 906 if (arrayElement == long.class || 907 arrayElement == double.class) 908 throw newIllegalArgumentException("array length is not legal for long[] or double[]", arrayLength); 909 } 910 } 911 912 /** 913 * Makes an <em>array-collecting</em> method handle, which accepts a given number of trailing 914 * positional arguments and collects them into an array argument. 915 * The new method handle adapts, as its <i>target</i>, 916 * the current method handle. The type of the adapter will be 917 * the same as the type of the target, except that a single trailing 918 * parameter (usually of type {@code arrayType}) is replaced by 919 * {@code arrayLength} parameters whose type is element type of {@code arrayType}. 920 * <p> 921 * If the array type differs from the final argument type on the original target, 922 * the original target is adapted to take the array type directly, 923 * as if by a call to {@link #asType asType}. 924 * <p> 925 * When called, the adapter replaces its trailing {@code arrayLength} 926 * arguments by a single new array of type {@code arrayType}, whose elements 927 * comprise (in order) the replaced arguments. 928 * Finally the target is called. 929 * What the target eventually returns is returned unchanged by the adapter. 930 * <p> 931 * (The array may also be a shared constant when {@code arrayLength} is zero.) 932 * <p> 933 * (<em>Note:</em> The {@code arrayType} is often identical to the last 934 * parameter type of the original target. 935 * It is an explicit argument for symmetry with {@code asSpreader}, and also 936 * to allow the target to use a simple {@code Object} as its last parameter type.) 937 * <p> 938 * In order to create a collecting adapter which is not restricted to a particular 939 * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead. 940 * <p> 941 * Here are some examples of array-collecting method handles: 942 * <blockquote><pre>{@code 943 MethodHandle deepToString = publicLookup() 944 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 945 assertEquals("[won]", (String) deepToString.invokeExact(new Object[]{"won"})); 946 MethodHandle ts1 = deepToString.asCollector(Object[].class, 1); 947 assertEquals(methodType(String.class, Object.class), ts1.type()); 948 //assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"})); //FAIL 949 assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"})); 950 // arrayType can be a subtype of Object[] 951 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 952 assertEquals(methodType(String.class, String.class, String.class), ts2.type()); 953 assertEquals("[two, too]", (String) ts2.invokeExact("two", "too")); 954 MethodHandle ts0 = deepToString.asCollector(Object[].class, 0); 955 assertEquals("[]", (String) ts0.invokeExact()); 956 // collectors can be nested, Lisp-style 957 MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2); 958 assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D"))); 959 // arrayType can be any primitive array type 960 MethodHandle bytesToString = publicLookup() 961 .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class)) 962 .asCollector(byte[].class, 3); 963 assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3)); 964 MethodHandle longsToString = publicLookup() 965 .findStatic(Arrays.class, "toString", methodType(String.class, long[].class)) 966 .asCollector(long[].class, 1); 967 assertEquals("[123]", (String) longsToString.invokeExact((long)123)); 968 * }</pre></blockquote> 969 * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments 970 * @param arrayLength the number of arguments to collect into a new array argument 971 * @return a new method handle which collects some trailing argument 972 * into an array, before calling the original method handle 973 * @throws NullPointerException if {@code arrayType} is a null reference 974 * @throws IllegalArgumentException if {@code arrayType} is not an array type 975 * or {@code arrayType} is not assignable to this method handle's trailing parameter type, 976 * or {@code arrayLength} is not a legal array size, 977 * or the resulting method handle's type would have 978 * <a href="MethodHandle.html#maxarity">too many parameters</a> 979 * @throws WrongMethodTypeException if the implied {@code asType} call fails 980 * @see #asSpreader 981 * @see #asVarargsCollector 982 */ 983 public MethodHandle asCollector(Class<?> arrayType, int arrayLength) { 984 asCollectorChecks(arrayType, arrayLength); 985 int collectArgPos = type().parameterCount()-1; 986 MethodHandle target = this; 987 if (arrayType != type().parameterType(collectArgPos)) 988 target = convertArguments(type().changeParameterType(collectArgPos, arrayType)); 989 MethodHandle collector = ValueConversions.varargsArray(arrayType, arrayLength); 990 return MethodHandles.collectArguments(target, collectArgPos, collector); 991 } 992 993 // private API: return true if last param exactly matches arrayType 994 private boolean asCollectorChecks(Class<?> arrayType, int arrayLength) { 995 spreadArrayChecks(arrayType, arrayLength); 996 int nargs = type().parameterCount(); 997 if (nargs != 0) { 998 Class<?> lastParam = type().parameterType(nargs-1); 999 if (lastParam == arrayType) return true; 1000 if (lastParam.isAssignableFrom(arrayType)) return false; 1001 } 1002 throw newIllegalArgumentException("array type not assignable to trailing argument", this, arrayType); 1003 } 1004 1005 /** 1006 * Makes a <em>variable arity</em> adapter which is able to accept 1007 * any number of trailing positional arguments and collect them 1008 * into an array argument. 1009 * <p> 1010 * The type and behavior of the adapter will be the same as 1011 * the type and behavior of the target, except that certain 1012 * {@code invoke} and {@code asType} requests can lead to 1013 * trailing positional arguments being collected into target's 1014 * trailing parameter. 1015 * Also, the last parameter type of the adapter will be 1016 * {@code arrayType}, even if the target has a different 1017 * last parameter type. 1018 * <p> 1019 * This transformation may return {@code this} if the method handle is 1020 * already of variable arity and its trailing parameter type 1021 * is identical to {@code arrayType}. 1022 * <p> 1023 * When called with {@link #invokeExact invokeExact}, the adapter invokes 1024 * the target with no argument changes. 1025 * (<em>Note:</em> This behavior is different from a 1026 * {@linkplain #asCollector fixed arity collector}, 1027 * since it accepts a whole array of indeterminate length, 1028 * rather than a fixed number of arguments.) 1029 * <p> 1030 * When called with plain, inexact {@link #invoke invoke}, if the caller 1031 * type is the same as the adapter, the adapter invokes the target as with 1032 * {@code invokeExact}. 1033 * (This is the normal behavior for {@code invoke} when types match.) 1034 * <p> 1035 * Otherwise, if the caller and adapter arity are the same, and the 1036 * trailing parameter type of the caller is a reference type identical to 1037 * or assignable to the trailing parameter type of the adapter, 1038 * the arguments and return values are converted pairwise, 1039 * as if by {@link #asType asType} on a fixed arity 1040 * method handle. 1041 * <p> 1042 * Otherwise, the arities differ, or the adapter's trailing parameter 1043 * type is not assignable from the corresponding caller type. 1044 * In this case, the adapter replaces all trailing arguments from 1045 * the original trailing argument position onward, by 1046 * a new array of type {@code arrayType}, whose elements 1047 * comprise (in order) the replaced arguments. 1048 * <p> 1049 * The caller type must provides as least enough arguments, 1050 * and of the correct type, to satisfy the target's requirement for 1051 * positional arguments before the trailing array argument. 1052 * Thus, the caller must supply, at a minimum, {@code N-1} arguments, 1053 * where {@code N} is the arity of the target. 1054 * Also, there must exist conversions from the incoming arguments 1055 * to the target's arguments. 1056 * As with other uses of plain {@code invoke}, if these basic 1057 * requirements are not fulfilled, a {@code WrongMethodTypeException} 1058 * may be thrown. 1059 * <p> 1060 * In all cases, what the target eventually returns is returned unchanged by the adapter. 1061 * <p> 1062 * In the final case, it is exactly as if the target method handle were 1063 * temporarily adapted with a {@linkplain #asCollector fixed arity collector} 1064 * to the arity required by the caller type. 1065 * (As with {@code asCollector}, if the array length is zero, 1066 * a shared constant may be used instead of a new array. 1067 * If the implied call to {@code asCollector} would throw 1068 * an {@code IllegalArgumentException} or {@code WrongMethodTypeException}, 1069 * the call to the variable arity adapter must throw 1070 * {@code WrongMethodTypeException}.) 1071 * <p> 1072 * The behavior of {@link #asType asType} is also specialized for 1073 * variable arity adapters, to maintain the invariant that 1074 * plain, inexact {@code invoke} is always equivalent to an {@code asType} 1075 * call to adjust the target type, followed by {@code invokeExact}. 1076 * Therefore, a variable arity adapter responds 1077 * to an {@code asType} request by building a fixed arity collector, 1078 * if and only if the adapter and requested type differ either 1079 * in arity or trailing argument type. 1080 * The resulting fixed arity collector has its type further adjusted 1081 * (if necessary) to the requested type by pairwise conversion, 1082 * as if by another application of {@code asType}. 1083 * <p> 1084 * When a method handle is obtained by executing an {@code ldc} instruction 1085 * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked 1086 * as a variable arity method (with the modifier bit {@code 0x0080}), 1087 * the method handle will accept multiple arities, as if the method handle 1088 * constant were created by means of a call to {@code asVarargsCollector}. 1089 * <p> 1090 * In order to create a collecting adapter which collects a predetermined 1091 * number of arguments, and whose type reflects this predetermined number, 1092 * use {@link #asCollector asCollector} instead. 1093 * <p> 1094 * No method handle transformations produce new method handles with 1095 * variable arity, unless they are documented as doing so. 1096 * Therefore, besides {@code asVarargsCollector}, 1097 * all methods in {@code MethodHandle} and {@code MethodHandles} 1098 * will return a method handle with fixed arity, 1099 * except in the cases where they are specified to return their original 1100 * operand (e.g., {@code asType} of the method handle's own type). 1101 * <p> 1102 * Calling {@code asVarargsCollector} on a method handle which is already 1103 * of variable arity will produce a method handle with the same type and behavior. 1104 * It may (or may not) return the original variable arity method handle. 1105 * <p> 1106 * Here is an example, of a list-making variable arity method handle: 1107 * <blockquote><pre>{@code 1108 MethodHandle deepToString = publicLookup() 1109 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 1110 MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class); 1111 assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"})); 1112 assertEquals("[won]", (String) ts1.invoke( new Object[]{"won"})); 1113 assertEquals("[won]", (String) ts1.invoke( "won" )); 1114 assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"})); 1115 // findStatic of Arrays.asList(...) produces a variable arity method handle: 1116 MethodHandle asList = publicLookup() 1117 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class)); 1118 assertEquals(methodType(List.class, Object[].class), asList.type()); 1119 assert(asList.isVarargsCollector()); 1120 assertEquals("[]", asList.invoke().toString()); 1121 assertEquals("[1]", asList.invoke(1).toString()); 1122 assertEquals("[two, too]", asList.invoke("two", "too").toString()); 1123 String[] argv = { "three", "thee", "tee" }; 1124 assertEquals("[three, thee, tee]", asList.invoke(argv).toString()); 1125 assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString()); 1126 List ls = (List) asList.invoke((Object)argv); 1127 assertEquals(1, ls.size()); 1128 assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0))); 1129 * }</pre></blockquote> 1130 * <p style="font-size:smaller;"> 1131 * <em>Discussion:</em> 1132 * These rules are designed as a dynamically-typed variation 1133 * of the Java rules for variable arity methods. 1134 * In both cases, callers to a variable arity method or method handle 1135 * can either pass zero or more positional arguments, or else pass 1136 * pre-collected arrays of any length. Users should be aware of the 1137 * special role of the final argument, and of the effect of a 1138 * type match on that final argument, which determines whether 1139 * or not a single trailing argument is interpreted as a whole 1140 * array or a single element of an array to be collected. 1141 * Note that the dynamic type of the trailing argument has no 1142 * effect on this decision, only a comparison between the symbolic 1143 * type descriptor of the call site and the type descriptor of the method handle.) 1144 * 1145 * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments 1146 * @return a new method handle which can collect any number of trailing arguments 1147 * into an array, before calling the original method handle 1148 * @throws NullPointerException if {@code arrayType} is a null reference 1149 * @throws IllegalArgumentException if {@code arrayType} is not an array type 1150 * or {@code arrayType} is not assignable to this method handle's trailing parameter type 1151 * @see #asCollector 1152 * @see #isVarargsCollector 1153 * @see #asFixedArity 1154 */ 1155 public MethodHandle asVarargsCollector(Class<?> arrayType) { 1156 Class<?> arrayElement = arrayType.getComponentType(); 1157 boolean lastMatch = asCollectorChecks(arrayType, 0); 1158 if (isVarargsCollector() && lastMatch) 1159 return this; 1160 return MethodHandleImpl.makeVarargsCollector(this, arrayType); 1161 } 1162 1163 /** 1164 * Determines if this method handle 1165 * supports {@linkplain #asVarargsCollector variable arity} calls. 1166 * Such method handles arise from the following sources: 1167 * <ul> 1168 * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector} 1169 * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method} 1170 * which resolves to a variable arity Java method or constructor 1171 * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle} 1172 * which resolves to a variable arity Java method or constructor 1173 * </ul> 1174 * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls 1175 * @see #asVarargsCollector 1176 * @see #asFixedArity 1177 */ 1178 public boolean isVarargsCollector() { 1179 return false; 1180 } 1181 1182 /** 1183 * Makes a <em>fixed arity</em> method handle which is otherwise 1184 * equivalent to the current method handle. 1185 * <p> 1186 * If the current method handle is not of 1187 * {@linkplain #asVarargsCollector variable arity}, 1188 * the current method handle is returned. 1189 * This is true even if the current method handle 1190 * could not be a valid input to {@code asVarargsCollector}. 1191 * <p> 1192 * Otherwise, the resulting fixed-arity method handle has the same 1193 * type and behavior of the current method handle, 1194 * except that {@link #isVarargsCollector isVarargsCollector} 1195 * will be false. 1196 * The fixed-arity method handle may (or may not) be the 1197 * a previous argument to {@code asVarargsCollector}. 1198 * <p> 1199 * Here is an example, of a list-making variable arity method handle: 1200 * <blockquote><pre>{@code 1201 MethodHandle asListVar = publicLookup() 1202 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class)) 1203 .asVarargsCollector(Object[].class); 1204 MethodHandle asListFix = asListVar.asFixedArity(); 1205 assertEquals("[1]", asListVar.invoke(1).toString()); 1206 Exception caught = null; 1207 try { asListFix.invoke((Object)1); } 1208 catch (Exception ex) { caught = ex; } 1209 assert(caught instanceof ClassCastException); 1210 assertEquals("[two, too]", asListVar.invoke("two", "too").toString()); 1211 try { asListFix.invoke("two", "too"); } 1212 catch (Exception ex) { caught = ex; } 1213 assert(caught instanceof WrongMethodTypeException); 1214 Object[] argv = { "three", "thee", "tee" }; 1215 assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString()); 1216 assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString()); 1217 assertEquals(1, ((List) asListVar.invoke((Object)argv)).size()); 1218 assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString()); 1219 * }</pre></blockquote> 1220 * 1221 * @return a new method handle which accepts only a fixed number of arguments 1222 * @see #asVarargsCollector 1223 * @see #isVarargsCollector 1224 */ 1225 public MethodHandle asFixedArity() { 1226 assert(!isVarargsCollector()); 1227 return this; 1228 } 1229 1230 /** 1231 * Binds a value {@code x} to the first argument of a method handle, without invoking it. 1232 * The new method handle adapts, as its <i>target</i>, 1233 * the current method handle by binding it to the given argument. 1234 * The type of the bound handle will be 1235 * the same as the type of the target, except that a single leading 1236 * reference parameter will be omitted. 1237 * <p> 1238 * When called, the bound handle inserts the given value {@code x} 1239 * as a new leading argument to the target. The other arguments are 1240 * also passed unchanged. 1241 * What the target eventually returns is returned unchanged by the bound handle. 1242 * <p> 1243 * The reference {@code x} must be convertible to the first parameter 1244 * type of the target. 1245 * <p> 1246 * (<em>Note:</em> Because method handles are immutable, the target method handle 1247 * retains its original type and behavior.) 1248 * @param x the value to bind to the first argument of the target 1249 * @return a new method handle which prepends the given value to the incoming 1250 * argument list, before calling the original method handle 1251 * @throws IllegalArgumentException if the target does not have a 1252 * leading parameter type that is a reference type 1253 * @throws ClassCastException if {@code x} cannot be converted 1254 * to the leading parameter type of the target 1255 * @see MethodHandles#insertArguments 1256 */ 1257 public MethodHandle bindTo(Object x) { 1258 Class<?> ptype; 1259 @SuppressWarnings("LocalVariableHidesMemberVariable") 1260 MethodType type = type(); 1261 if (type.parameterCount() == 0 || 1262 (ptype = type.parameterType(0)).isPrimitive()) 1263 throw newIllegalArgumentException("no leading reference parameter", x); 1264 x = ptype.cast(x); // throw CCE if needed 1265 return bindReceiver(x); 1266 } 1267 1268 /** 1269 * Returns a string representation of the method handle, 1270 * starting with the string {@code "MethodHandle"} and 1271 * ending with the string representation of the method handle's type. 1272 * In other words, this method returns a string equal to the value of: 1273 * <blockquote><pre>{@code 1274 * "MethodHandle" + type().toString() 1275 * }</pre></blockquote> 1276 * <p> 1277 * (<em>Note:</em> Future releases of this API may add further information 1278 * to the string representation. 1279 * Therefore, the present syntax should not be parsed by applications.) 1280 * 1281 * @return a string representation of the method handle 1282 */ 1283 @Override 1284 public String toString() { 1285 if (DEBUG_METHOD_HANDLE_NAMES) return debugString(); 1286 return standardString(); 1287 } 1288 String standardString() { 1289 return "MethodHandle"+type; 1290 } 1291 String debugString() { 1292 return standardString()+"/LF="+internalForm()+internalProperties(); 1293 } 1294 1295 //// Implementation methods. 1296 //// Sub-classes can override these default implementations. 1297 //// All these methods assume arguments are already validated. 1298 1299 // Other transforms to do: convert, explicitCast, permute, drop, filter, fold, GWT, catch 1300 1301 /*non-public*/ 1302 MethodHandle setVarargs(MemberName member) throws IllegalAccessException { 1303 if (!member.isVarargs()) return this; 1304 int argc = type().parameterCount(); 1305 if (argc != 0) { 1306 Class<?> arrayType = type().parameterType(argc-1); 1307 if (arrayType.isArray()) { 1308 return MethodHandleImpl.makeVarargsCollector(this, arrayType); 1309 } 1310 } 1311 throw member.makeAccessException("cannot make variable arity", null); 1312 } 1313 /*non-public*/ 1314 MethodHandle viewAsType(MethodType newType) { 1315 // No actual conversions, just a new view of the same method. 1316 return MethodHandleImpl.makePairwiseConvert(this, newType, 0); 1317 } 1318 1319 // Decoding 1320 1321 /*non-public*/ 1322 LambdaForm internalForm() { 1323 return form; 1324 } 1325 1326 /*non-public*/ 1327 MemberName internalMemberName() { 1328 return null; // DMH returns DMH.member 1329 } 1330 1331 /*non-public*/ 1332 Class<?> internalCallerClass() { 1333 return null; // caller-bound MH for @CallerSensitive method returns caller 1334 } 1335 1336 /*non-public*/ 1337 MethodHandle withInternalMemberName(MemberName member) { 1338 if (member != null) { 1339 return MethodHandleImpl.makeWrappedMember(this, member); 1340 } else if (internalMemberName() == null) { 1341 // The required internaMemberName is null, and this MH (like most) doesn't have one. 1342 return this; 1343 } else { 1344 // The following case is rare. Mask the internalMemberName by wrapping the MH in a BMH. 1345 MethodHandle result = rebind(); 1346 assert (result.internalMemberName() == null); 1347 return result; 1348 } 1349 } 1350 1351 /*non-public*/ 1352 boolean isInvokeSpecial() { 1353 return false; // DMH.Special returns true 1354 } 1355 1356 /*non-public*/ 1357 Object internalValues() { 1358 return null; 1359 } 1360 1361 /*non-public*/ 1362 Object internalProperties() { 1363 // Override to something like "/FOO=bar" 1364 return ""; 1365 } 1366 1367 //// Method handle implementation methods. 1368 //// Sub-classes can override these default implementations. 1369 //// All these methods assume arguments are already validated. 1370 1371 /*non-public*/ MethodHandle convertArguments(MethodType newType) { 1372 // Override this if it can be improved. 1373 return MethodHandleImpl.makePairwiseConvert(this, newType, 1); 1374 } 1375 1376 /*non-public*/ 1377 MethodHandle bindArgument(int pos, char basicType, Object value) { 1378 // Override this if it can be improved. 1379 return rebind().bindArgument(pos, basicType, value); 1380 } 1381 1382 /*non-public*/ 1383 MethodHandle bindReceiver(Object receiver) { 1384 // Override this if it can be improved. 1385 return bindArgument(0, 'L', receiver); 1386 } 1387 1388 /*non-public*/ 1389 MethodHandle bindImmediate(int pos, char basicType, Object value) { 1390 // Bind an immediate value to a position in the arguments. 1391 // This means, elide the respective argument, 1392 // and replace all references to it in NamedFunction args with the specified value. 1393 1394 // CURRENT RESTRICTIONS 1395 // * only for pos 0 and UNSAFE (position is adjusted in MHImpl to make API usable for others) 1396 assert pos == 0 && basicType == 'L' && value instanceof Unsafe; 1397 MethodType type2 = type.dropParameterTypes(pos, pos + 1); // adjustment: ignore receiver! 1398 LambdaForm form2 = form.bindImmediate(pos + 1, basicType, value); // adjust pos to form-relative pos 1399 return copyWith(type2, form2); 1400 } 1401 1402 /*non-public*/ 1403 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 1404 throw new InternalError("copyWith: " + this.getClass()); 1405 } 1406 1407 /*non-public*/ 1408 MethodHandle dropArguments(MethodType srcType, int pos, int drops) { 1409 // Override this if it can be improved. 1410 return rebind().dropArguments(srcType, pos, drops); 1411 } 1412 1413 /*non-public*/ 1414 MethodHandle permuteArguments(MethodType newType, int[] reorder) { 1415 // Override this if it can be improved. 1416 return rebind().permuteArguments(newType, reorder); 1417 } 1418 1419 /*non-public*/ 1420 MethodHandle rebind() { 1421 // Bind 'this' into a new invoker, of the known class BMH. 1422 MethodType type2 = type(); 1423 LambdaForm form2 = reinvokerForm(this); 1424 // form2 = lambda (bmh, arg*) { thismh = bmh[0]; invokeBasic(thismh, arg*) } 1425 return BoundMethodHandle.bindSingle(type2, form2, this); 1426 } 1427 1428 /*non-public*/ 1429 MethodHandle reinvokerTarget() { 1430 throw new InternalError("not a reinvoker MH: "+this.getClass().getName()+": "+this); 1431 } 1432 1433 /** Create a LF which simply reinvokes a target of the given basic type. 1434 * The target MH must override {@link #reinvokerTarget} to provide the target. 1435 */ 1436 static LambdaForm reinvokerForm(MethodHandle target) { 1437 MethodType mtype = target.type().basicType(); 1438 LambdaForm reinvoker = mtype.form().cachedLambdaForm(MethodTypeForm.LF_REINVOKE); 1439 if (reinvoker != null) return reinvoker; 1440 if (mtype.parameterSlotCount() >= MethodType.MAX_MH_ARITY) 1441 return makeReinvokerForm(target.type(), target); // cannot cache this 1442 reinvoker = makeReinvokerForm(mtype, null); 1443 return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_REINVOKE, reinvoker); 1444 } 1445 private static LambdaForm makeReinvokerForm(MethodType mtype, MethodHandle customTargetOrNull) { 1446 boolean customized = (customTargetOrNull != null); 1447 MethodHandle MH_invokeBasic = customized ? null : MethodHandles.basicInvoker(mtype); 1448 final int THIS_BMH = 0; 1449 final int ARG_BASE = 1; 1450 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 1451 int nameCursor = ARG_LIMIT; 1452 final int NEXT_MH = customized ? -1 : nameCursor++; 1453 final int REINVOKE = nameCursor++; 1454 LambdaForm.Name[] names = LambdaForm.arguments(nameCursor - ARG_LIMIT, mtype.invokerType()); 1455 Object[] targetArgs; 1456 MethodHandle targetMH; 1457 if (customized) { 1458 targetArgs = Arrays.copyOfRange(names, ARG_BASE, ARG_LIMIT, Object[].class); 1459 targetMH = customTargetOrNull; 1460 } else { 1461 names[NEXT_MH] = new LambdaForm.Name(NF_reinvokerTarget, names[THIS_BMH]); 1462 targetArgs = Arrays.copyOfRange(names, THIS_BMH, ARG_LIMIT, Object[].class); 1463 targetArgs[0] = names[NEXT_MH]; // overwrite this MH with next MH 1464 targetMH = MethodHandles.basicInvoker(mtype); 1465 } 1466 names[REINVOKE] = new LambdaForm.Name(targetMH, targetArgs); 1467 return new LambdaForm("BMH.reinvoke", ARG_LIMIT, names); 1468 } 1469 1470 private static final LambdaForm.NamedFunction NF_reinvokerTarget; 1471 static { 1472 try { 1473 NF_reinvokerTarget = new LambdaForm.NamedFunction(MethodHandle.class 1474 .getDeclaredMethod("reinvokerTarget")); 1475 } catch (ReflectiveOperationException ex) { 1476 throw newInternalError(ex); 1477 } 1478 } 1479 1480 /** 1481 * Replace the old lambda form of this method handle with a new one. 1482 * The new one must be functionally equivalent to the old one. 1483 * Threads may continue running the old form indefinitely, 1484 * but it is likely that the new one will be preferred for new executions. 1485 * Use with discretion. 1486 */ 1487 /*non-public*/ 1488 void updateForm(LambdaForm newForm) { 1489 if (form == newForm) return; 1490 // ISSUE: Should we have a memory fence here? 1491 UNSAFE.putObject(this, FORM_OFFSET, newForm); 1492 this.form.prepare(); // as in MethodHandle.<init> 1493 } 1494 1495 private static final long FORM_OFFSET; 1496 static { 1497 try { 1498 FORM_OFFSET = UNSAFE.objectFieldOffset(MethodHandle.class.getDeclaredField("form")); 1499 } catch (ReflectiveOperationException ex) { 1500 throw newInternalError(ex); 1501 } 1502 } 1503 }