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