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