1 /* 2 * Copyright (c) 2008, 2019, 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 * <h2>Method handle contents</h2> 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 * <h2>Method handle compilation</h2> 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 * <h2>Method handle invocation</h2> 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 * <h2>Invocation checking</h2> 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 * <h2>Method handle creation</h2> 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 {@jvms 4.4.8} and {@jvms 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 * <h2>Usage examples</h2> 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 * <h2>Exceptions</h2> 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 * <h2><a id="sigpoly"></a>Signature polymorphism</h2> 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 * <h2>Interoperation between method handles and the Core Reflection API</h2> 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 * <h2>Interoperation between method handles and Java generics</h2> 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 * <h2><a id="maxarity"></a>Arity limits</h2> 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*/ 452 final LambdaForm form; 453 // form is not private so that invokers can easily fetch it 454 /*private*/ 455 MethodHandle asTypeCache; 456 // asTypeCache is not private so that invokers can easily fetch it 457 /*non-public*/ 458 byte customizationCount; 459 // customizationCount should be accessible from invokers 460 461 /** 462 * Reports the type of this method handle. 463 * Every invocation of this method handle via {@code invokeExact} must exactly match this type. 464 * @return the method handle type 465 */ 466 public MethodType type() { 467 return type; 468 } 469 470 /** 471 * Package-private constructor for the method handle implementation hierarchy. 472 * Method handle inheritance will be contained completely within 473 * the {@code java.lang.invoke} package. 474 */ 475 // @param type type (permanently assigned) of the new method handle 476 /*non-public*/ 477 MethodHandle(MethodType type, LambdaForm form) { 478 this.type = Objects.requireNonNull(type); 479 this.form = Objects.requireNonNull(form).uncustomize(); 480 481 this.form.prepare(); // TO DO: Try to delay this step until just before invocation. 482 } 483 484 /** 485 * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match. 486 * The symbolic type descriptor at the call site of {@code invokeExact} must 487 * exactly match this method handle's {@link #type() type}. 488 * No conversions are allowed on arguments or return values. 489 * <p> 490 * When this method is observed via the Core Reflection API, 491 * it will appear as a single native method, taking an object array and returning an object. 492 * If this native method is invoked directly via 493 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI, 494 * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}, 495 * it will throw an {@code UnsupportedOperationException}. 496 * @param args the signature-polymorphic parameter list, statically represented using varargs 497 * @return the signature-polymorphic result, statically represented using {@code Object} 498 * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor 499 * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call 500 */ 501 @HotSpotIntrinsicCandidate 502 public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable; 503 504 /** 505 * Invokes the method handle, allowing any caller type descriptor, 506 * and optionally performing conversions on arguments and return values. 507 * <p> 508 * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type() type}, 509 * the call proceeds as if by {@link #invokeExact invokeExact}. 510 * <p> 511 * Otherwise, the call proceeds as if this method handle were first 512 * adjusted by calling {@link #asType asType} to adjust this method handle 513 * to the required type, and then the call proceeds as if by 514 * {@link #invokeExact invokeExact} on the adjusted method handle. 515 * <p> 516 * There is no guarantee that the {@code asType} call is actually made. 517 * If the JVM can predict the results of making the call, it may perform 518 * adaptations directly on the caller's arguments, 519 * and call the target method handle according to its own exact type. 520 * <p> 521 * The resolved type descriptor at the call site of {@code invoke} must 522 * be a valid argument to the receivers {@code asType} method. 523 * In particular, the caller must specify the same argument arity 524 * as the callee's type, 525 * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}. 526 * <p> 527 * When this method is observed via the Core Reflection API, 528 * it will appear as a single native method, taking an object array and returning an object. 529 * If this native method is invoked directly via 530 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI, 531 * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}, 532 * it will throw an {@code UnsupportedOperationException}. 533 * @param args the signature-polymorphic parameter list, statically represented using varargs 534 * @return the signature-polymorphic result, statically represented using {@code Object} 535 * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor 536 * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails 537 * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call 538 */ 539 @HotSpotIntrinsicCandidate 540 public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable; 541 542 /** 543 * Private method for trusted invocation of a method handle respecting simplified signatures. 544 * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM. 545 * <p> 546 * The caller signature is restricted to the following basic types: 547 * Object, int, long, float, double, and void return. 548 * <p> 549 * The caller is responsible for maintaining type correctness by ensuring 550 * that the each outgoing argument value is a member of the range of the corresponding 551 * callee argument type. 552 * (The caller should therefore issue appropriate casts and integer narrowing 553 * operations on outgoing argument values.) 554 * The caller can assume that the incoming result value is part of the range 555 * of the callee's return type. 556 * @param args the signature-polymorphic parameter list, statically represented using varargs 557 * @return the signature-polymorphic result, statically represented using {@code Object} 558 */ 559 @HotSpotIntrinsicCandidate 560 /*non-public*/ 561 final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable; 562 563 /** 564 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}. 565 * The caller signature is restricted to basic types as with {@code invokeBasic}. 566 * The trailing (not leading) argument must be a MemberName. 567 * @param args the signature-polymorphic parameter list, statically represented using varargs 568 * @return the signature-polymorphic result, statically represented using {@code Object} 569 */ 570 @HotSpotIntrinsicCandidate 571 /*non-public*/ 572 static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable; 573 574 /** 575 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}. 576 * The caller signature is restricted to basic types as with {@code invokeBasic}. 577 * The trailing (not leading) argument must be a MemberName. 578 * @param args the signature-polymorphic parameter list, statically represented using varargs 579 * @return the signature-polymorphic result, statically represented using {@code Object} 580 */ 581 @HotSpotIntrinsicCandidate 582 /*non-public*/ 583 static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable; 584 585 /** 586 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}. 587 * The caller signature is restricted to basic types as with {@code invokeBasic}. 588 * The trailing (not leading) argument must be a MemberName. 589 * @param args the signature-polymorphic parameter list, statically represented using varargs 590 * @return the signature-polymorphic result, statically represented using {@code Object} 591 */ 592 @HotSpotIntrinsicCandidate 593 /*non-public*/ 594 static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable; 595 596 /** 597 * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}. 598 * The caller signature is restricted to basic types as with {@code invokeBasic}. 599 * The trailing (not leading) argument must be a MemberName. 600 * @param args the signature-polymorphic parameter list, statically represented using varargs 601 * @return the signature-polymorphic result, statically represented using {@code Object} 602 */ 603 @HotSpotIntrinsicCandidate 604 /*non-public*/ 605 static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable; 606 607 /** 608 * Performs a variable arity invocation, passing the arguments in the given array 609 * to the method handle, as if via an inexact {@link #invoke invoke} from a call site 610 * which mentions only the type {@code Object}, and whose actual argument count is the length 611 * of the argument array. 612 * <p> 613 * Specifically, execution proceeds as if by the following steps, 614 * although the methods are not guaranteed to be called if the JVM 615 * can predict their effects. 616 * <ul> 617 * <li>Determine the length of the argument array as {@code N}. 618 * For a null reference, {@code N=0}. </li> 619 * <li>Collect the {@code N} elements of the array as a logical 620 * argument list, each argument statically typed as an {@code Object}. </li> 621 * <li>Determine, as {@code M}, the parameter count of the type of this 622 * method handle. </li> 623 * <li>Determine the general type {@code TN} of {@code N} arguments or 624 * {@code M} arguments, if smaller than {@code N}, as 625 * {@code TN=MethodType.genericMethodType(Math.min(N, M))}.</li> 626 * <li>If {@code N} is greater than {@code M}, perform the following 627 * checks and actions to shorten the logical argument list: <ul> 628 * <li>Check that this method handle has variable arity with a 629 * {@linkplain MethodType#lastParameterType trailing parameter} 630 * of some array type {@code A[]}. If not, fail with a 631 * {@code WrongMethodTypeException}. </li> 632 * <li>Collect the trailing elements (there are {@code N-M+1} of them) 633 * from the logical argument list into a single array of 634 * type {@code A[]}, using {@code asType} conversions to 635 * convert each trailing argument to type {@code A}. </li> 636 * <li>If any of these conversions proves impossible, fail with either 637 * a {@code ClassCastException} if any trailing element cannot be 638 * cast to {@code A} or a {@code NullPointerException} if any 639 * trailing element is {@code null} and {@code A} is not a reference 640 * type. </li> 641 * <li>Replace the logical arguments gathered into the array of 642 * type {@code A[]} with the array itself, thus shortening 643 * the argument list to length {@code M}. This final argument 644 * retains the static type {@code A[]}.</li> 645 * <li>Adjust the type {@code TN} by changing the {@code N}th 646 * parameter type from {@code Object} to {@code A[]}. 647 * </ul> 648 * <li>Force the original target method handle {@code MH0} to the 649 * required type, as {@code MH1 = MH0.asType(TN)}. </li> 650 * <li>Spread the argument list into {@code N} separate arguments {@code A0, ...}. </li> 651 * <li>Invoke the type-adjusted method handle on the unpacked arguments: 652 * MH1.invokeExact(A0, ...). </li> 653 * <li>Take the return value as an {@code Object} reference. </li> 654 * </ul> 655 * <p> 656 * If the target method handle has variable arity, and the argument list is longer 657 * than that arity, the excess arguments, starting at the position of the trailing 658 * array argument, will be gathered (if possible, as if by {@code asType} conversions) 659 * into an array of the appropriate type, and invocation will proceed on the 660 * shortened argument list. 661 * In this way, <em>jumbo argument lists</em> which would spread into more 662 * than 254 slots can still be processed uniformly. 663 * <p> 664 * Unlike the {@link #invoke(Object...) generic} invocation mode, which can 665 * "recycle" an array argument, passing it directly to the target method, 666 * this invocation mode <em>always</em> creates a new array parameter, even 667 * if the original array passed to {@code invokeWithArguments} would have 668 * been acceptable as a direct argument to the target method. 669 * Even if the number {@code M} of actual arguments is the arity {@code N}, 670 * and the last argument is dynamically a suitable array of type {@code A[]}, 671 * it will still be boxed into a new one-element array, since the call 672 * site statically types the argument as {@code Object}, not an array type. 673 * This is not a special rule for this method, but rather a regular effect 674 * of the {@linkplain #asVarargsCollector rules for variable-arity invocation}. 675 * <p> 676 * Because of the action of the {@code asType} step, the following argument 677 * conversions are applied as necessary: 678 * <ul> 679 * <li>reference casting 680 * <li>unboxing 681 * <li>widening primitive conversions 682 * <li>variable arity conversion 683 * </ul> 684 * <p> 685 * The result returned by the call is boxed if it is a primitive, 686 * or forced to null if the return type is void. 687 * <p> 688 * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke}, 689 * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI. 690 * It can therefore be used as a bridge between native or reflective code and method handles. 691 * @apiNote 692 * This call is approximately equivalent to the following code: 693 * <blockquote><pre>{@code 694 * // for jumbo argument lists, adapt varargs explicitly: 695 * int N = (arguments == null? 0: arguments.length); 696 * int M = this.type.parameterCount(); 697 * int MAX_SAFE = 127; // 127 longs require 254 slots, which is OK 698 * if (N > MAX_SAFE && N > M && this.isVarargsCollector()) { 699 * Class<?> arrayType = this.type().lastParameterType(); 700 * Class<?> elemType = arrayType.getComponentType(); 701 * if (elemType != null) { 702 * Object args2 = Array.newInstance(elemType, M); 703 * MethodHandle arraySetter = MethodHandles.arrayElementSetter(arrayType); 704 * for (int i = 0; i < M; i++) { 705 * arraySetter.invoke(args2, i, arguments[M-1 + i]); 706 * } 707 * arguments = Arrays.copyOf(arguments, M); 708 * arguments[M-1] = args2; 709 * return this.asFixedArity().invokeWithArguments(arguments); 710 * } 711 * } // done with explicit varargs processing 712 * 713 * // Handle fixed arity and non-jumbo variable arity invocation. 714 * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0); 715 * Object result = invoker.invokeExact(this, arguments); 716 * }</pre></blockquote> 717 * 718 * @param arguments the arguments to pass to the target 719 * @return the result returned by the target 720 * @throws ClassCastException if an argument cannot be converted by reference casting 721 * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments 722 * @throws Throwable anything thrown by the target method invocation 723 * @see MethodHandles#spreadInvoker 724 */ 725 public Object invokeWithArguments(Object... arguments) throws Throwable { 726 // Note: Jumbo argument lists are handled in the variable-arity subclass. 727 MethodType invocationType = MethodType.genericMethodType(arguments == null ? 0 : arguments.length); 728 return invocationType.invokers().spreadInvoker(0).invokeExact(asType(invocationType), arguments); 729 } 730 731 /** 732 * Performs a variable arity invocation, passing the arguments in the given list 733 * to the method handle, as if via an inexact {@link #invoke invoke} from a call site 734 * which mentions only the type {@code Object}, and whose actual argument count is the length 735 * of the argument list. 736 * <p> 737 * This method is also equivalent to the following code: 738 * <blockquote><pre>{@code 739 * invokeWithArguments(arguments.toArray()) 740 * }</pre></blockquote> 741 * <p> 742 * Jumbo-sized lists are acceptable if this method handle has variable arity. 743 * See {@link #invokeWithArguments(Object[])} for details. 744 * 745 * @param arguments the arguments to pass to the target 746 * @return the result returned by the target 747 * @throws NullPointerException if {@code arguments} is a null reference 748 * @throws ClassCastException if an argument cannot be converted by reference casting 749 * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments 750 * @throws Throwable anything thrown by the target method invocation 751 */ 752 public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable { 753 return invokeWithArguments(arguments.toArray()); 754 } 755 756 /** 757 * Produces an adapter method handle which adapts the type of the 758 * current method handle to a new type. 759 * The resulting method handle is guaranteed to report a type 760 * which is equal to the desired new type. 761 * <p> 762 * If the original type and new type are equal, returns {@code this}. 763 * <p> 764 * The new method handle, when invoked, will perform the following 765 * steps: 766 * <ul> 767 * <li>Convert the incoming argument list to match the original 768 * method handle's argument list. 769 * <li>Invoke the original method handle on the converted argument list. 770 * <li>Convert any result returned by the original method handle 771 * to the return type of new method handle. 772 * </ul> 773 * <p> 774 * This method provides the crucial behavioral difference between 775 * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}. 776 * The two methods 777 * perform the same steps when the caller's type descriptor exactly matches 778 * the callee's, but when the types differ, plain {@link #invoke invoke} 779 * also calls {@code asType} (or some internal equivalent) in order 780 * to match up the caller's and callee's types. 781 * <p> 782 * If the current method is a variable arity method handle 783 * argument list conversion may involve the conversion and collection 784 * of several arguments into an array, as 785 * {@linkplain #asVarargsCollector described elsewhere}. 786 * In every other case, all conversions are applied <em>pairwise</em>, 787 * which means that each argument or return value is converted to 788 * exactly one argument or return value (or no return value). 789 * The applied conversions are defined by consulting 790 * the corresponding component types of the old and new 791 * method handle types. 792 * <p> 793 * Let <em>T0</em> and <em>T1</em> be corresponding new and old parameter types, 794 * or old and new return types. Specifically, for some valid index {@code i}, let 795 * <em>T0</em>{@code =newType.parameterType(i)} and <em>T1</em>{@code =this.type().parameterType(i)}. 796 * Or else, going the other way for return values, let 797 * <em>T0</em>{@code =this.type().returnType()} and <em>T1</em>{@code =newType.returnType()}. 798 * If the types are the same, the new method handle makes no change 799 * to the corresponding argument or return value (if any). 800 * Otherwise, one of the following conversions is applied 801 * if possible: 802 * <ul> 803 * <li>If <em>T0</em> and <em>T1</em> are references, then a cast to <em>T1</em> is applied. 804 * (The types do not need to be related in any particular way. 805 * This is because a dynamic value of null can convert to any reference type.) 806 * <li>If <em>T0</em> and <em>T1</em> are primitives, then a Java method invocation 807 * conversion (JLS 5.3) is applied, if one exists. 808 * (Specifically, <em>T0</em> must convert to <em>T1</em> by a widening primitive conversion.) 809 * <li>If <em>T0</em> is a primitive and <em>T1</em> a reference, 810 * a Java casting conversion (JLS 5.5) is applied if one exists. 811 * (Specifically, the value is boxed from <em>T0</em> to its wrapper class, 812 * which is then widened as needed to <em>T1</em>.) 813 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 814 * conversion will be applied at runtime, possibly followed 815 * by a Java method invocation conversion (JLS 5.3) 816 * on the primitive value. (These are the primitive widening conversions.) 817 * <em>T0</em> must be a wrapper class or a supertype of one. 818 * (In the case where <em>T0</em> is Object, these are the conversions 819 * allowed by {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.) 820 * The unboxing conversion must have a possibility of success, which means that 821 * if <em>T0</em> is not itself a wrapper class, there must exist at least one 822 * wrapper class <em>TW</em> which is a subtype of <em>T0</em> and whose unboxed 823 * primitive value can be widened to <em>T1</em>. 824 * <li>If the return type <em>T1</em> is marked as void, any returned value is discarded 825 * <li>If the return type <em>T0</em> is void and <em>T1</em> a reference, a null value is introduced. 826 * <li>If the return type <em>T0</em> is void and <em>T1</em> a primitive, 827 * a zero value is introduced. 828 * </ul> 829 * (<em>Note:</em> Both <em>T0</em> and <em>T1</em> may be regarded as static types, 830 * because neither corresponds specifically to the <em>dynamic type</em> of any 831 * actual argument or return value.) 832 * <p> 833 * The method handle conversion cannot be made if any one of the required 834 * pairwise conversions cannot be made. 835 * <p> 836 * At runtime, the conversions applied to reference arguments 837 * or return values may require additional runtime checks which can fail. 838 * An unboxing operation may fail because the original reference is null, 839 * causing a {@link java.lang.NullPointerException NullPointerException}. 840 * An unboxing operation or a reference cast may also fail on a reference 841 * to an object of the wrong type, 842 * causing a {@link java.lang.ClassCastException ClassCastException}. 843 * Although an unboxing operation may accept several kinds of wrappers, 844 * if none are available, a {@code ClassCastException} will be thrown. 845 * 846 * @param newType the expected type of the new method handle 847 * @return a method handle which delegates to {@code this} after performing 848 * any necessary argument conversions, and arranges for any 849 * necessary return value conversions 850 * @throws NullPointerException if {@code newType} is a null reference 851 * @throws WrongMethodTypeException if the conversion cannot be made 852 * @see MethodHandles#explicitCastArguments 853 */ 854 public MethodHandle asType(MethodType newType) { 855 // Fast path alternative to a heavyweight {@code asType} call. 856 // Return 'this' if the conversion will be a no-op. 857 if (newType == type) { 858 return this; 859 } 860 // Return 'this.asTypeCache' if the conversion is already memoized. 861 MethodHandle atc = asTypeCached(newType); 862 if (atc != null) { 863 return atc; 864 } 865 return asTypeUncached(newType); 866 } 867 868 private MethodHandle asTypeCached(MethodType newType) { 869 MethodHandle atc = asTypeCache; 870 if (atc != null && newType == atc.type) { 871 return atc; 872 } 873 return null; 874 } 875 876 /** Override this to change asType behavior. */ 877 /*non-public*/ 878 MethodHandle asTypeUncached(MethodType newType) { 879 if (!type.isConvertibleTo(newType)) 880 throw new WrongMethodTypeException("cannot convert "+this+" to "+newType); 881 return asTypeCache = MethodHandleImpl.makePairwiseConvert(this, newType, true); 882 } 883 884 /** 885 * Makes an <em>array-spreading</em> method handle, which accepts a trailing array argument 886 * and spreads its elements as positional arguments. 887 * The new method handle adapts, as its <i>target</i>, 888 * the current method handle. The type of the adapter will be 889 * the same as the type of the target, except that the final 890 * {@code arrayLength} parameters of the target's type are replaced 891 * by a single array parameter of type {@code arrayType}. 892 * <p> 893 * If the array element type differs from any of the corresponding 894 * argument types on the original target, 895 * the original target is adapted to take the array elements directly, 896 * as if by a call to {@link #asType asType}. 897 * <p> 898 * When called, the adapter replaces a trailing array argument 899 * by the array's elements, each as its own argument to the target. 900 * (The order of the arguments is preserved.) 901 * They are converted pairwise by casting and/or unboxing 902 * to the types of the trailing parameters of the target. 903 * Finally the target is called. 904 * What the target eventually returns is returned unchanged by the adapter. 905 * <p> 906 * Before calling the target, the adapter verifies that the array 907 * contains exactly enough elements to provide a correct argument count 908 * to the target method handle. 909 * (The array may also be null when zero elements are required.) 910 * <p> 911 * When the adapter is called, the length of the supplied {@code array} 912 * argument is queried as if by {@code array.length} or {@code arraylength} 913 * bytecode. If the adapter accepts a zero-length trailing array argument, 914 * the supplied {@code array} argument can either be a zero-length array or 915 * {@code null}; otherwise, the adapter will throw a {@code NullPointerException} 916 * if the array is {@code null} and throw an {@link IllegalArgumentException} 917 * if the array does not have the correct number of elements. 918 * <p> 919 * Here are some simple examples of array-spreading method handles: 920 * <blockquote><pre>{@code 921 MethodHandle equals = publicLookup() 922 .findVirtual(String.class, "equals", methodType(boolean.class, Object.class)); 923 assert( (boolean) equals.invokeExact("me", (Object)"me")); 924 assert(!(boolean) equals.invokeExact("me", (Object)"thee")); 925 // spread both arguments from a 2-array: 926 MethodHandle eq2 = equals.asSpreader(Object[].class, 2); 927 assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" })); 928 assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" })); 929 // try to spread from anything but a 2-array: 930 for (int n = 0; n <= 10; n++) { 931 Object[] badArityArgs = (n == 2 ? new Object[0] : new Object[n]); 932 try { assert((boolean) eq2.invokeExact(badArityArgs) && false); } 933 catch (IllegalArgumentException ex) { } // OK 934 } 935 // spread both arguments from a String array: 936 MethodHandle eq2s = equals.asSpreader(String[].class, 2); 937 assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" })); 938 assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" })); 939 // spread second arguments from a 1-array: 940 MethodHandle eq1 = equals.asSpreader(Object[].class, 1); 941 assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" })); 942 assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" })); 943 // spread no arguments from a 0-array or null: 944 MethodHandle eq0 = equals.asSpreader(Object[].class, 0); 945 assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0])); 946 assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null)); 947 // asSpreader and asCollector are approximate inverses: 948 for (int n = 0; n <= 2; n++) { 949 for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) { 950 MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n); 951 assert( (boolean) equals2.invokeWithArguments("me", "me")); 952 assert(!(boolean) equals2.invokeWithArguments("me", "thee")); 953 } 954 } 955 MethodHandle caToString = publicLookup() 956 .findStatic(Arrays.class, "toString", methodType(String.class, char[].class)); 957 assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray())); 958 MethodHandle caString3 = caToString.asCollector(char[].class, 3); 959 assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C')); 960 MethodHandle caToString2 = caString3.asSpreader(char[].class, 2); 961 assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray())); 962 * }</pre></blockquote> 963 * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments 964 * @param arrayLength the number of arguments to spread from an incoming array argument 965 * @return a new method handle which spreads its final array argument, 966 * before calling the original method handle 967 * @throws NullPointerException if {@code arrayType} is a null reference 968 * @throws IllegalArgumentException if {@code arrayType} is not an array type, 969 * or if target does not have at least 970 * {@code arrayLength} parameter types, 971 * or if {@code arrayLength} is negative, 972 * or if the resulting method handle's type would have 973 * <a href="MethodHandle.html#maxarity">too many parameters</a> 974 * @throws WrongMethodTypeException if the implied {@code asType} call fails 975 * @see #asCollector 976 */ 977 public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) { 978 return asSpreader(type().parameterCount() - arrayLength, arrayType, arrayLength); 979 } 980 981 /** 982 * Makes an <em>array-spreading</em> method handle, which accepts an array argument at a given position and spreads 983 * its elements as positional arguments in place of the array. The new method handle adapts, as its <i>target</i>, 984 * the current method handle. The type of the adapter will be the same as the type of the target, except that the 985 * {@code arrayLength} parameters of the target's type, starting at the zero-based position {@code spreadArgPos}, 986 * are replaced by a single array parameter of type {@code arrayType}. 987 * <p> 988 * This method behaves very much like {@link #asSpreader(Class, int)}, but accepts an additional {@code spreadArgPos} 989 * argument to indicate at which position in the parameter list the spreading should take place. 990 * 991 * @apiNote Example: 992 * <blockquote><pre>{@code 993 MethodHandle compare = LOOKUP.findStatic(Objects.class, "compare", methodType(int.class, Object.class, Object.class, Comparator.class)); 994 MethodHandle compare2FromArray = compare.asSpreader(0, Object[].class, 2); 995 Object[] ints = new Object[]{3, 9, 7, 7}; 996 Comparator<Integer> cmp = (a, b) -> a - b; 997 assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 0, 2), cmp) < 0); 998 assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 1, 3), cmp) > 0); 999 assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 2, 4), cmp) == 0); 1000 * }</pre></blockquote> 1001 * @param spreadArgPos the position (zero-based index) in the argument list at which spreading should start. 1002 * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments 1003 * @param arrayLength the number of arguments to spread from an incoming array argument 1004 * @return a new method handle which spreads an array argument at a given position, 1005 * before calling the original method handle 1006 * @throws NullPointerException if {@code arrayType} is a null reference 1007 * @throws IllegalArgumentException if {@code arrayType} is not an array type, 1008 * or if target does not have at least 1009 * {@code arrayLength} parameter types, 1010 * or if {@code arrayLength} is negative, 1011 * or if {@code spreadArgPos} has an illegal value (negative, or together with arrayLength exceeding the 1012 * number of arguments), 1013 * or if the resulting method handle's type would have 1014 * <a href="MethodHandle.html#maxarity">too many parameters</a> 1015 * @throws WrongMethodTypeException if the implied {@code asType} call fails 1016 * 1017 * @see #asSpreader(Class, int) 1018 * @since 9 1019 */ 1020 public MethodHandle asSpreader(int spreadArgPos, Class<?> arrayType, int arrayLength) { 1021 MethodType postSpreadType = asSpreaderChecks(arrayType, spreadArgPos, arrayLength); 1022 MethodHandle afterSpread = this.asType(postSpreadType); 1023 BoundMethodHandle mh = afterSpread.rebind(); 1024 LambdaForm lform = mh.editor().spreadArgumentsForm(1 + spreadArgPos, arrayType, arrayLength); 1025 MethodType preSpreadType = postSpreadType.replaceParameterTypes(spreadArgPos, spreadArgPos + arrayLength, arrayType); 1026 return mh.copyWith(preSpreadType, lform); 1027 } 1028 1029 /** 1030 * See if {@code asSpreader} can be validly called with the given arguments. 1031 * Return the type of the method handle call after spreading but before conversions. 1032 */ 1033 private MethodType asSpreaderChecks(Class<?> arrayType, int pos, int arrayLength) { 1034 spreadArrayChecks(arrayType, arrayLength); 1035 int nargs = type().parameterCount(); 1036 if (nargs < arrayLength || arrayLength < 0) 1037 throw newIllegalArgumentException("bad spread array length"); 1038 if (pos < 0 || pos + arrayLength > nargs) { 1039 throw newIllegalArgumentException("bad spread position"); 1040 } 1041 Class<?> arrayElement = arrayType.getComponentType(); 1042 MethodType mtype = type(); 1043 boolean match = true, fail = false; 1044 for (int i = pos; i < pos + arrayLength; i++) { 1045 Class<?> ptype = mtype.parameterType(i); 1046 if (ptype != arrayElement) { 1047 match = false; 1048 if (!MethodType.canConvert(arrayElement, ptype)) { 1049 fail = true; 1050 break; 1051 } 1052 } 1053 } 1054 if (match) return mtype; 1055 MethodType needType = mtype.asSpreaderType(arrayType, pos, arrayLength); 1056 if (!fail) return needType; 1057 // elicit an error: 1058 this.asType(needType); 1059 throw newInternalError("should not return"); 1060 } 1061 1062 private void spreadArrayChecks(Class<?> arrayType, int arrayLength) { 1063 Class<?> arrayElement = arrayType.getComponentType(); 1064 if (arrayElement == null) 1065 throw newIllegalArgumentException("not an array type", arrayType); 1066 if ((arrayLength & 0x7F) != arrayLength) { 1067 if ((arrayLength & 0xFF) != arrayLength) 1068 throw newIllegalArgumentException("array length is not legal", arrayLength); 1069 assert(arrayLength >= 128); 1070 if (arrayElement == long.class || 1071 arrayElement == double.class) 1072 throw newIllegalArgumentException("array length is not legal for long[] or double[]", arrayLength); 1073 } 1074 } 1075 /** 1076 * Adapts this method handle to be {@linkplain #asVarargsCollector variable arity} 1077 * if the boolean flag is true, else {@linkplain #asFixedArity fixed arity}. 1078 * If the method handle is already of the proper arity mode, it is returned 1079 * unchanged. 1080 * @apiNote 1081 * <p>This method is sometimes useful when adapting a method handle that 1082 * may be variable arity, to ensure that the resulting adapter is also 1083 * variable arity if and only if the original handle was. For example, 1084 * this code changes the first argument of a handle {@code mh} to {@code int} without 1085 * disturbing its variable arity property: 1086 * {@code mh.asType(mh.type().changeParameterType(0,int.class)) 1087 * .withVarargs(mh.isVarargsCollector())} 1088 * <p> 1089 * This call is approximately equivalent to the following code: 1090 * <blockquote><pre>{@code 1091 * if (makeVarargs == isVarargsCollector()) 1092 * return this; 1093 * else if (makeVarargs) 1094 * return asVarargsCollector(type().lastParameterType()); 1095 * else 1096 * return asFixedArity(); 1097 * }</pre></blockquote> 1098 * @param makeVarargs true if the return method handle should have variable arity behavior 1099 * @return a method handle of the same type, with possibly adjusted variable arity behavior 1100 * @throws IllegalArgumentException if {@code makeVarargs} is true and 1101 * this method handle does not have a trailing array parameter 1102 * @since 9 1103 * @see #asVarargsCollector 1104 * @see #asFixedArity 1105 */ 1106 public MethodHandle withVarargs(boolean makeVarargs) { 1107 assert(!isVarargsCollector()); // subclass responsibility 1108 if (makeVarargs) { 1109 return asVarargsCollector(type().lastParameterType()); 1110 } else { 1111 return this; 1112 } 1113 } 1114 1115 /** 1116 * Makes an <em>array-collecting</em> method handle, which accepts a given number of trailing 1117 * positional arguments and collects them into an array argument. 1118 * The new method handle adapts, as its <i>target</i>, 1119 * the current method handle. The type of the adapter will be 1120 * the same as the type of the target, except that a single trailing 1121 * parameter (usually of type {@code arrayType}) is replaced by 1122 * {@code arrayLength} parameters whose type is element type of {@code arrayType}. 1123 * <p> 1124 * If the array type differs from the final argument type on the original target, 1125 * the original target is adapted to take the array type directly, 1126 * as if by a call to {@link #asType asType}. 1127 * <p> 1128 * When called, the adapter replaces its trailing {@code arrayLength} 1129 * arguments by a single new array of type {@code arrayType}, whose elements 1130 * comprise (in order) the replaced arguments. 1131 * Finally the target is called. 1132 * What the target eventually returns is returned unchanged by the adapter. 1133 * <p> 1134 * (The array may also be a shared constant when {@code arrayLength} is zero.) 1135 * <p> 1136 * (<em>Note:</em> The {@code arrayType} is often identical to the 1137 * {@linkplain MethodType#lastParameterType last parameter type} 1138 * of the original target. 1139 * It is an explicit argument for symmetry with {@code asSpreader}, and also 1140 * to allow the target to use a simple {@code Object} as its last parameter type.) 1141 * <p> 1142 * In order to create a collecting adapter which is not restricted to a particular 1143 * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} 1144 * or {@link #withVarargs withVarargs} instead. 1145 * <p> 1146 * Here are some examples of array-collecting method handles: 1147 * <blockquote><pre>{@code 1148 MethodHandle deepToString = publicLookup() 1149 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 1150 assertEquals("[won]", (String) deepToString.invokeExact(new Object[]{"won"})); 1151 MethodHandle ts1 = deepToString.asCollector(Object[].class, 1); 1152 assertEquals(methodType(String.class, Object.class), ts1.type()); 1153 //assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"})); //FAIL 1154 assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"})); 1155 // arrayType can be a subtype of Object[] 1156 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 1157 assertEquals(methodType(String.class, String.class, String.class), ts2.type()); 1158 assertEquals("[two, too]", (String) ts2.invokeExact("two", "too")); 1159 MethodHandle ts0 = deepToString.asCollector(Object[].class, 0); 1160 assertEquals("[]", (String) ts0.invokeExact()); 1161 // collectors can be nested, Lisp-style 1162 MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2); 1163 assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D"))); 1164 // arrayType can be any primitive array type 1165 MethodHandle bytesToString = publicLookup() 1166 .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class)) 1167 .asCollector(byte[].class, 3); 1168 assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3)); 1169 MethodHandle longsToString = publicLookup() 1170 .findStatic(Arrays.class, "toString", methodType(String.class, long[].class)) 1171 .asCollector(long[].class, 1); 1172 assertEquals("[123]", (String) longsToString.invokeExact((long)123)); 1173 * }</pre></blockquote> 1174 * <p> 1175 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 1176 * variable-arity method handle}, even if the original target method handle was. 1177 * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments 1178 * @param arrayLength the number of arguments to collect into a new array argument 1179 * @return a new method handle which collects some trailing argument 1180 * into an array, before calling the original method handle 1181 * @throws NullPointerException if {@code arrayType} is a null reference 1182 * @throws IllegalArgumentException if {@code arrayType} is not an array type 1183 * or {@code arrayType} is not assignable to this method handle's trailing parameter type, 1184 * or {@code arrayLength} is not a legal array size, 1185 * or the resulting method handle's type would have 1186 * <a href="MethodHandle.html#maxarity">too many parameters</a> 1187 * @throws WrongMethodTypeException if the implied {@code asType} call fails 1188 * @see #asSpreader 1189 * @see #asVarargsCollector 1190 */ 1191 public MethodHandle asCollector(Class<?> arrayType, int arrayLength) { 1192 return asCollector(type().parameterCount() - 1, arrayType, arrayLength); 1193 } 1194 1195 /** 1196 * Makes an <em>array-collecting</em> method handle, which accepts a given number of positional arguments starting 1197 * at a given position, and collects them into an array argument. The new method handle adapts, as its 1198 * <i>target</i>, the current method handle. The type of the adapter will be the same as the type of the target, 1199 * except that the parameter at the position indicated by {@code collectArgPos} (usually of type {@code arrayType}) 1200 * is replaced by {@code arrayLength} parameters whose type is element type of {@code arrayType}. 1201 * <p> 1202 * This method behaves very much like {@link #asCollector(Class, int)}, but differs in that its {@code 1203 * collectArgPos} argument indicates at which position in the parameter list arguments should be collected. This 1204 * index is zero-based. 1205 * 1206 * @apiNote Examples: 1207 * <blockquote><pre>{@code 1208 StringWriter swr = new StringWriter(); 1209 MethodHandle swWrite = LOOKUP.findVirtual(StringWriter.class, "write", methodType(void.class, char[].class, int.class, int.class)).bindTo(swr); 1210 MethodHandle swWrite4 = swWrite.asCollector(0, char[].class, 4); 1211 swWrite4.invoke('A', 'B', 'C', 'D', 1, 2); 1212 assertEquals("BC", swr.toString()); 1213 swWrite4.invoke('P', 'Q', 'R', 'S', 0, 4); 1214 assertEquals("BCPQRS", swr.toString()); 1215 swWrite4.invoke('W', 'X', 'Y', 'Z', 3, 1); 1216 assertEquals("BCPQRSZ", swr.toString()); 1217 * }</pre></blockquote> 1218 * <p> 1219 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 1220 * variable-arity method handle}, even if the original target method handle was. 1221 * @param collectArgPos the zero-based position in the parameter list at which to start collecting. 1222 * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments 1223 * @param arrayLength the number of arguments to collect into a new array argument 1224 * @return a new method handle which collects some arguments 1225 * into an array, before calling the original method handle 1226 * @throws NullPointerException if {@code arrayType} is a null reference 1227 * @throws IllegalArgumentException if {@code arrayType} is not an array type 1228 * or {@code arrayType} is not assignable to this method handle's array parameter type, 1229 * or {@code arrayLength} is not a legal array size, 1230 * or {@code collectArgPos} has an illegal value (negative, or greater than the number of arguments), 1231 * or the resulting method handle's type would have 1232 * <a href="MethodHandle.html#maxarity">too many parameters</a> 1233 * @throws WrongMethodTypeException if the implied {@code asType} call fails 1234 * 1235 * @see #asCollector(Class, int) 1236 * @since 9 1237 */ 1238 public MethodHandle asCollector(int collectArgPos, Class<?> arrayType, int arrayLength) { 1239 asCollectorChecks(arrayType, collectArgPos, arrayLength); 1240 BoundMethodHandle mh = rebind(); 1241 MethodType resultType = type().asCollectorType(arrayType, collectArgPos, arrayLength); 1242 MethodHandle newArray = MethodHandleImpl.varargsArray(arrayType, arrayLength); 1243 LambdaForm lform = mh.editor().collectArgumentArrayForm(1 + collectArgPos, newArray); 1244 if (lform != null) { 1245 return mh.copyWith(resultType, lform); 1246 } 1247 lform = mh.editor().collectArgumentsForm(1 + collectArgPos, newArray.type().basicType()); 1248 return mh.copyWithExtendL(resultType, lform, newArray); 1249 } 1250 1251 /** 1252 * See if {@code asCollector} can be validly called with the given arguments. 1253 * Return false if the last parameter is not an exact match to arrayType. 1254 */ 1255 /*non-public*/ 1256 boolean asCollectorChecks(Class<?> arrayType, int pos, int arrayLength) { 1257 spreadArrayChecks(arrayType, arrayLength); 1258 int nargs = type().parameterCount(); 1259 if (pos < 0 || pos >= nargs) { 1260 throw newIllegalArgumentException("bad collect position"); 1261 } 1262 if (nargs != 0) { 1263 Class<?> param = type().parameterType(pos); 1264 if (param == arrayType) return true; 1265 if (param.isAssignableFrom(arrayType)) return false; 1266 } 1267 throw newIllegalArgumentException("array type not assignable to argument", this, arrayType); 1268 } 1269 1270 /** 1271 * Makes a <em>variable arity</em> adapter which is able to accept 1272 * any number of trailing positional arguments and collect them 1273 * into an array argument. 1274 * <p> 1275 * The type and behavior of the adapter will be the same as 1276 * the type and behavior of the target, except that certain 1277 * {@code invoke} and {@code asType} requests can lead to 1278 * trailing positional arguments being collected into target's 1279 * trailing parameter. 1280 * Also, the 1281 * {@linkplain MethodType#lastParameterType last parameter type} 1282 * of the adapter will be 1283 * {@code arrayType}, even if the target has a different 1284 * last parameter type. 1285 * <p> 1286 * This transformation may return {@code this} if the method handle is 1287 * already of variable arity and its trailing parameter type 1288 * is identical to {@code arrayType}. 1289 * <p> 1290 * When called with {@link #invokeExact invokeExact}, the adapter invokes 1291 * the target with no argument changes. 1292 * (<em>Note:</em> This behavior is different from a 1293 * {@linkplain #asCollector fixed arity collector}, 1294 * since it accepts a whole array of indeterminate length, 1295 * rather than a fixed number of arguments.) 1296 * <p> 1297 * When called with plain, inexact {@link #invoke invoke}, if the caller 1298 * type is the same as the adapter, the adapter invokes the target as with 1299 * {@code invokeExact}. 1300 * (This is the normal behavior for {@code invoke} when types match.) 1301 * <p> 1302 * Otherwise, if the caller and adapter arity are the same, and the 1303 * trailing parameter type of the caller is a reference type identical to 1304 * or assignable to the trailing parameter type of the adapter, 1305 * the arguments and return values are converted pairwise, 1306 * as if by {@link #asType asType} on a fixed arity 1307 * method handle. 1308 * <p> 1309 * Otherwise, the arities differ, or the adapter's trailing parameter 1310 * type is not assignable from the corresponding caller type. 1311 * In this case, the adapter replaces all trailing arguments from 1312 * the original trailing argument position onward, by 1313 * a new array of type {@code arrayType}, whose elements 1314 * comprise (in order) the replaced arguments. 1315 * <p> 1316 * The caller type must provides as least enough arguments, 1317 * and of the correct type, to satisfy the target's requirement for 1318 * positional arguments before the trailing array argument. 1319 * Thus, the caller must supply, at a minimum, {@code N-1} arguments, 1320 * where {@code N} is the arity of the target. 1321 * Also, there must exist conversions from the incoming arguments 1322 * to the target's arguments. 1323 * As with other uses of plain {@code invoke}, if these basic 1324 * requirements are not fulfilled, a {@code WrongMethodTypeException} 1325 * may be thrown. 1326 * <p> 1327 * In all cases, what the target eventually returns is returned unchanged by the adapter. 1328 * <p> 1329 * In the final case, it is exactly as if the target method handle were 1330 * temporarily adapted with a {@linkplain #asCollector fixed arity collector} 1331 * to the arity required by the caller type. 1332 * (As with {@code asCollector}, if the array length is zero, 1333 * a shared constant may be used instead of a new array. 1334 * If the implied call to {@code asCollector} would throw 1335 * an {@code IllegalArgumentException} or {@code WrongMethodTypeException}, 1336 * the call to the variable arity adapter must throw 1337 * {@code WrongMethodTypeException}.) 1338 * <p> 1339 * The behavior of {@link #asType asType} is also specialized for 1340 * variable arity adapters, to maintain the invariant that 1341 * plain, inexact {@code invoke} is always equivalent to an {@code asType} 1342 * call to adjust the target type, followed by {@code invokeExact}. 1343 * Therefore, a variable arity adapter responds 1344 * to an {@code asType} request by building a fixed arity collector, 1345 * if and only if the adapter and requested type differ either 1346 * in arity or trailing argument type. 1347 * The resulting fixed arity collector has its type further adjusted 1348 * (if necessary) to the requested type by pairwise conversion, 1349 * as if by another application of {@code asType}. 1350 * <p> 1351 * When a method handle is obtained by executing an {@code ldc} instruction 1352 * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked 1353 * as a variable arity method (with the modifier bit {@code 0x0080}), 1354 * the method handle will accept multiple arities, as if the method handle 1355 * constant were created by means of a call to {@code asVarargsCollector}. 1356 * <p> 1357 * In order to create a collecting adapter which collects a predetermined 1358 * number of arguments, and whose type reflects this predetermined number, 1359 * use {@link #asCollector asCollector} instead. 1360 * <p> 1361 * No method handle transformations produce new method handles with 1362 * variable arity, unless they are documented as doing so. 1363 * Therefore, besides {@code asVarargsCollector} and {@code withVarargs}, 1364 * all methods in {@code MethodHandle} and {@code MethodHandles} 1365 * will return a method handle with fixed arity, 1366 * except in the cases where they are specified to return their original 1367 * operand (e.g., {@code asType} of the method handle's own type). 1368 * <p> 1369 * Calling {@code asVarargsCollector} on a method handle which is already 1370 * of variable arity will produce a method handle with the same type and behavior. 1371 * It may (or may not) return the original variable arity method handle. 1372 * <p> 1373 * Here is an example, of a list-making variable arity method handle: 1374 * <blockquote><pre>{@code 1375 MethodHandle deepToString = publicLookup() 1376 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 1377 MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class); 1378 assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"})); 1379 assertEquals("[won]", (String) ts1.invoke( new Object[]{"won"})); 1380 assertEquals("[won]", (String) ts1.invoke( "won" )); 1381 assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"})); 1382 // findStatic of Arrays.asList(...) produces a variable arity method handle: 1383 MethodHandle asList = publicLookup() 1384 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class)); 1385 assertEquals(methodType(List.class, Object[].class), asList.type()); 1386 assert(asList.isVarargsCollector()); 1387 assertEquals("[]", asList.invoke().toString()); 1388 assertEquals("[1]", asList.invoke(1).toString()); 1389 assertEquals("[two, too]", asList.invoke("two", "too").toString()); 1390 String[] argv = { "three", "thee", "tee" }; 1391 assertEquals("[three, thee, tee]", asList.invoke(argv).toString()); 1392 assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString()); 1393 List ls = (List) asList.invoke((Object)argv); 1394 assertEquals(1, ls.size()); 1395 assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0))); 1396 * }</pre></blockquote> 1397 * <p style="font-size:smaller;"> 1398 * <em>Discussion:</em> 1399 * These rules are designed as a dynamically-typed variation 1400 * of the Java rules for variable arity methods. 1401 * In both cases, callers to a variable arity method or method handle 1402 * can either pass zero or more positional arguments, or else pass 1403 * pre-collected arrays of any length. Users should be aware of the 1404 * special role of the final argument, and of the effect of a 1405 * type match on that final argument, which determines whether 1406 * or not a single trailing argument is interpreted as a whole 1407 * array or a single element of an array to be collected. 1408 * Note that the dynamic type of the trailing argument has no 1409 * effect on this decision, only a comparison between the symbolic 1410 * type descriptor of the call site and the type descriptor of the method handle.) 1411 * 1412 * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments 1413 * @return a new method handle which can collect any number of trailing arguments 1414 * into an array, before calling the original method handle 1415 * @throws NullPointerException if {@code arrayType} is a null reference 1416 * @throws IllegalArgumentException if {@code arrayType} is not an array type 1417 * or {@code arrayType} is not assignable to this method handle's trailing parameter type 1418 * @see #asCollector 1419 * @see #isVarargsCollector 1420 * @see #withVarargs 1421 * @see #asFixedArity 1422 */ 1423 public MethodHandle asVarargsCollector(Class<?> arrayType) { 1424 Objects.requireNonNull(arrayType); 1425 boolean lastMatch = asCollectorChecks(arrayType, type().parameterCount() - 1, 0); 1426 if (isVarargsCollector() && lastMatch) 1427 return this; 1428 return MethodHandleImpl.makeVarargsCollector(this, arrayType); 1429 } 1430 1431 /** 1432 * Determines if this method handle 1433 * supports {@linkplain #asVarargsCollector variable arity} calls. 1434 * Such method handles arise from the following sources: 1435 * <ul> 1436 * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector} 1437 * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method} 1438 * which resolves to a variable arity Java method or constructor 1439 * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle} 1440 * which resolves to a variable arity Java method or constructor 1441 * </ul> 1442 * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls 1443 * @see #asVarargsCollector 1444 * @see #asFixedArity 1445 */ 1446 public boolean isVarargsCollector() { 1447 return false; 1448 } 1449 1450 /** 1451 * Makes a <em>fixed arity</em> method handle which is otherwise 1452 * equivalent to the current method handle. 1453 * <p> 1454 * If the current method handle is not of 1455 * {@linkplain #asVarargsCollector variable arity}, 1456 * the current method handle is returned. 1457 * This is true even if the current method handle 1458 * could not be a valid input to {@code asVarargsCollector}. 1459 * <p> 1460 * Otherwise, the resulting fixed-arity method handle has the same 1461 * type and behavior of the current method handle, 1462 * except that {@link #isVarargsCollector isVarargsCollector} 1463 * will be false. 1464 * The fixed-arity method handle may (or may not) be the 1465 * a previous argument to {@code asVarargsCollector}. 1466 * <p> 1467 * Here is an example, of a list-making variable arity method handle: 1468 * <blockquote><pre>{@code 1469 MethodHandle asListVar = publicLookup() 1470 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class)) 1471 .asVarargsCollector(Object[].class); 1472 MethodHandle asListFix = asListVar.asFixedArity(); 1473 assertEquals("[1]", asListVar.invoke(1).toString()); 1474 Exception caught = null; 1475 try { asListFix.invoke((Object)1); } 1476 catch (Exception ex) { caught = ex; } 1477 assert(caught instanceof ClassCastException); 1478 assertEquals("[two, too]", asListVar.invoke("two", "too").toString()); 1479 try { asListFix.invoke("two", "too"); } 1480 catch (Exception ex) { caught = ex; } 1481 assert(caught instanceof WrongMethodTypeException); 1482 Object[] argv = { "three", "thee", "tee" }; 1483 assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString()); 1484 assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString()); 1485 assertEquals(1, ((List) asListVar.invoke((Object)argv)).size()); 1486 assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString()); 1487 * }</pre></blockquote> 1488 * 1489 * @return a new method handle which accepts only a fixed number of arguments 1490 * @see #asVarargsCollector 1491 * @see #isVarargsCollector 1492 * @see #withVarargs 1493 */ 1494 public MethodHandle asFixedArity() { 1495 assert(!isVarargsCollector()); 1496 return this; 1497 } 1498 1499 /** 1500 * Binds a value {@code x} to the first argument of a method handle, without invoking it. 1501 * The new method handle adapts, as its <i>target</i>, 1502 * the current method handle by binding it to the given argument. 1503 * The type of the bound handle will be 1504 * the same as the type of the target, except that a single leading 1505 * reference parameter will be omitted. 1506 * <p> 1507 * When called, the bound handle inserts the given value {@code x} 1508 * as a new leading argument to the target. The other arguments are 1509 * also passed unchanged. 1510 * What the target eventually returns is returned unchanged by the bound handle. 1511 * <p> 1512 * The reference {@code x} must be convertible to the first parameter 1513 * type of the target. 1514 * <p> 1515 * <em>Note:</em> Because method handles are immutable, the target method handle 1516 * retains its original type and behavior. 1517 * <p> 1518 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 1519 * variable-arity method handle}, even if the original target method handle was. 1520 * @param x the value to bind to the first argument of the target 1521 * @return a new method handle which prepends the given value to the incoming 1522 * argument list, before calling the original method handle 1523 * @throws IllegalArgumentException if the target does not have a 1524 * leading parameter type that is a reference type 1525 * @throws ClassCastException if {@code x} cannot be converted 1526 * to the leading parameter type of the target 1527 * @see MethodHandles#insertArguments 1528 */ 1529 public MethodHandle bindTo(Object x) { 1530 x = type.leadingReferenceParameter().cast(x); // throw CCE if needed 1531 return bindArgumentL(0, x); 1532 } 1533 1534 /** 1535 * Return a nominal descriptor for this instance, if one can be 1536 * constructed, or an empty {@link Optional} if one cannot be. 1537 * 1538 * @return An {@link Optional} containing the resulting nominal descriptor, 1539 * or an empty {@link Optional} if one cannot be constructed. 1540 * @since 12 1541 */ 1542 @Override 1543 public Optional<MethodHandleDesc> describeConstable() { 1544 MethodHandleInfo info; 1545 ClassDesc owner; 1546 String name; 1547 MethodTypeDesc type; 1548 boolean isInterface; 1549 try { 1550 info = IMPL_LOOKUP.revealDirect(this); 1551 isInterface = info.getDeclaringClass().isInterface(); 1552 owner = info.getDeclaringClass().describeConstable().orElseThrow(); 1553 type = info.getMethodType().describeConstable().orElseThrow(); 1554 name = info.getName(); 1555 } 1556 catch (Exception e) { 1557 return Optional.empty(); 1558 } 1559 1560 switch (info.getReferenceKind()) { 1561 case REF_getField: 1562 return Optional.of(MethodHandleDesc.ofField(DirectMethodHandleDesc.Kind.GETTER, owner, name, type.returnType())); 1563 case REF_putField: 1564 return Optional.of(MethodHandleDesc.ofField(DirectMethodHandleDesc.Kind.SETTER, owner, name, type.parameterType(0))); 1565 case REF_getStatic: 1566 return Optional.of(MethodHandleDesc.ofField(DirectMethodHandleDesc.Kind.STATIC_GETTER, owner, name, type.returnType())); 1567 case REF_putStatic: 1568 return Optional.of(MethodHandleDesc.ofField(DirectMethodHandleDesc.Kind.STATIC_SETTER, owner, name, type.parameterType(0))); 1569 case REF_invokeVirtual: 1570 return Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.VIRTUAL, owner, name, type)); 1571 case REF_invokeStatic: 1572 return isInterface ? 1573 Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.INTERFACE_STATIC, owner, name, type)) : 1574 Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.STATIC, owner, name, type)); 1575 case REF_invokeSpecial: 1576 return isInterface ? 1577 Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.INTERFACE_SPECIAL, owner, name, type)) : 1578 Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.SPECIAL, owner, name, type)); 1579 case REF_invokeInterface: 1580 return Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.INTERFACE_VIRTUAL, owner, name, type)); 1581 case REF_newInvokeSpecial: 1582 return Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.CONSTRUCTOR, owner, name, type)); 1583 default: 1584 return Optional.empty(); 1585 } 1586 } 1587 1588 /** 1589 * Returns a string representation of the method handle, 1590 * starting with the string {@code "MethodHandle"} and 1591 * ending with the string representation of the method handle's type. 1592 * In other words, this method returns a string equal to the value of: 1593 * <blockquote><pre>{@code 1594 * "MethodHandle" + type().toString() 1595 * }</pre></blockquote> 1596 * <p> 1597 * (<em>Note:</em> Future releases of this API may add further information 1598 * to the string representation. 1599 * Therefore, the present syntax should not be parsed by applications.) 1600 * 1601 * @return a string representation of the method handle 1602 */ 1603 @Override 1604 public String toString() { 1605 if (DEBUG_METHOD_HANDLE_NAMES) return "MethodHandle"+debugString(); 1606 return standardString(); 1607 } 1608 String standardString() { 1609 return "MethodHandle"+type; 1610 } 1611 /** Return a string with a several lines describing the method handle structure. 1612 * This string would be suitable for display in an IDE debugger. 1613 */ 1614 String debugString() { 1615 return type+" : "+internalForm()+internalProperties(); 1616 } 1617 1618 //// Implementation methods. 1619 //// Sub-classes can override these default implementations. 1620 //// All these methods assume arguments are already validated. 1621 1622 // Other transforms to do: convert, explicitCast, permute, drop, filter, fold, GWT, catch 1623 1624 BoundMethodHandle bindArgumentL(int pos, Object value) { 1625 return rebind().bindArgumentL(pos, value); 1626 } 1627 1628 /*non-public*/ 1629 MethodHandle setVarargs(MemberName member) throws IllegalAccessException { 1630 if (!member.isVarargs()) return this; 1631 try { 1632 return this.withVarargs(true); 1633 } catch (IllegalArgumentException ex) { 1634 throw member.makeAccessException("cannot make variable arity", null); 1635 } 1636 } 1637 1638 /*non-public*/ 1639 MethodHandle viewAsType(MethodType newType, boolean strict) { 1640 // No actual conversions, just a new view of the same method. 1641 // Note that this operation must not produce a DirectMethodHandle, 1642 // because retyped DMHs, like any transformed MHs, 1643 // cannot be cracked into MethodHandleInfo. 1644 assert viewAsTypeChecks(newType, strict); 1645 BoundMethodHandle mh = rebind(); 1646 return mh.copyWith(newType, mh.form); 1647 } 1648 1649 /*non-public*/ 1650 boolean viewAsTypeChecks(MethodType newType, boolean strict) { 1651 if (strict) { 1652 assert(type().isViewableAs(newType, true)) 1653 : Arrays.asList(this, newType); 1654 } else { 1655 assert(type().basicType().isViewableAs(newType.basicType(), true)) 1656 : Arrays.asList(this, newType); 1657 } 1658 return true; 1659 } 1660 1661 // Decoding 1662 1663 /*non-public*/ 1664 LambdaForm internalForm() { 1665 return form; 1666 } 1667 1668 /*non-public*/ 1669 MemberName internalMemberName() { 1670 return null; // DMH returns DMH.member 1671 } 1672 1673 /*non-public*/ 1674 Class<?> internalCallerClass() { 1675 return null; // caller-bound MH for @CallerSensitive method returns caller 1676 } 1677 1678 /*non-public*/ 1679 MethodHandleImpl.Intrinsic intrinsicName() { 1680 // no special intrinsic meaning to most MHs 1681 return MethodHandleImpl.Intrinsic.NONE; 1682 } 1683 1684 /*non-public*/ 1685 MethodHandle withInternalMemberName(MemberName member, boolean isInvokeSpecial) { 1686 if (member != null) { 1687 return MethodHandleImpl.makeWrappedMember(this, member, isInvokeSpecial); 1688 } else if (internalMemberName() == null) { 1689 // The required internaMemberName is null, and this MH (like most) doesn't have one. 1690 return this; 1691 } else { 1692 // The following case is rare. Mask the internalMemberName by wrapping the MH in a BMH. 1693 MethodHandle result = rebind(); 1694 assert (result.internalMemberName() == null); 1695 return result; 1696 } 1697 } 1698 1699 /*non-public*/ 1700 boolean isInvokeSpecial() { 1701 return false; // DMH.Special returns true 1702 } 1703 1704 /*non-public*/ 1705 Object internalValues() { 1706 return null; 1707 } 1708 1709 /*non-public*/ 1710 Object internalProperties() { 1711 // Override to something to follow this.form, like "\n& FOO=bar" 1712 return ""; 1713 } 1714 1715 //// Method handle implementation methods. 1716 //// Sub-classes can override these default implementations. 1717 //// All these methods assume arguments are already validated. 1718 1719 /*non-public*/ 1720 abstract MethodHandle copyWith(MethodType mt, LambdaForm lf); 1721 1722 /** Require this method handle to be a BMH, or else replace it with a "wrapper" BMH. 1723 * Many transforms are implemented only for BMHs. 1724 * @return a behaviorally equivalent BMH 1725 */ 1726 abstract BoundMethodHandle rebind(); 1727 1728 /** 1729 * Replace the old lambda form of this method handle with a new one. 1730 * The new one must be functionally equivalent to the old one. 1731 * Threads may continue running the old form indefinitely, 1732 * but it is likely that the new one will be preferred for new executions. 1733 * Use with discretion. 1734 */ 1735 /*non-public*/ 1736 void updateForm(LambdaForm newForm) { 1737 assert(newForm.customized == null || newForm.customized == this); 1738 if (form == newForm) return; 1739 newForm.prepare(); // as in MethodHandle.<init> 1740 UNSAFE.putReference(this, FORM_OFFSET, newForm); 1741 UNSAFE.fullFence(); 1742 } 1743 1744 /** Craft a LambdaForm customized for this particular MethodHandle */ 1745 /*non-public*/ 1746 void customize() { 1747 final LambdaForm form = this.form; 1748 if (form.customized == null) { 1749 LambdaForm newForm = form.customize(this); 1750 updateForm(newForm); 1751 } else { 1752 assert(form.customized == this); 1753 } 1754 } 1755 1756 private static final long FORM_OFFSET 1757 = UNSAFE.objectFieldOffset(MethodHandle.class, "form"); 1758 }