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