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