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