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