Home » openjdk-7 » java.lang.invoke » [javadoc | source]

    1   /*
    2    * Copyright (c) 2008, 2011, 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.ArrayList;
   30   import sun.invoke.util.ValueConversions;
   31   import static java.lang.invoke.MethodHandleStatics.*;
   32   
   33   /**
   34    * A method handle is a typed, directly executable reference to an underlying method,
   35    * constructor, field, or similar low-level operation, with optional
   36    * transformations of arguments or return values.
   37    * These transformations are quite general, and include such patterns as
   38    * {@linkplain #asType conversion},
   39    * {@linkplain #bindTo insertion},
   40    * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
   41    * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
   42    *
   43    * <h3>Method handle contents</h3>
   44    * Method handles are dynamically and strongly typed according to their parameter and return types.
   45    * They are not distinguished by the name or the defining class of their underlying methods.
   46    * A method handle must be invoked using a symbolic type descriptor which matches
   47    * the method handle's own {@linkplain #type type descriptor}.
   48    * <p>
   49    * Every method handle reports its type descriptor via the {@link #type type} accessor.
   50    * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
   51    * whose structure is a series of classes, one of which is
   52    * the return type of the method (or {@code void.class} if none).
   53    * <p>
   54    * A method handle's type controls the types of invocations it accepts,
   55    * and the kinds of transformations that apply to it.
   56    * <p>
   57    * A method handle contains a pair of special invoker methods
   58    * called {@link #invokeExact invokeExact} and {@link #invoke invoke}.
   59    * Both invoker methods provide direct access to the method handle's
   60    * underlying method, constructor, field, or other operation,
   61    * as modified by transformations of arguments and return values.
   62    * Both invokers accept calls which exactly match the method handle's own type.
   63    * The plain, inexact invoker also accepts a range of other call types.
   64    * <p>
   65    * Method handles are immutable and have no visible state.
   66    * Of course, they can be bound to underlying methods or data which exhibit state.
   67    * With respect to the Java Memory Model, any method handle will behave
   68    * as if all of its (internal) fields are final variables.  This means that any method
   69    * handle made visible to the application will always be fully formed.
   70    * This is true even if the method handle is published through a shared
   71    * variable in a data race.
   72    * <p>
   73    * Method handles cannot be subclassed by the user.
   74    * Implementations may (or may not) create internal subclasses of {@code MethodHandle}
   75    * which may be visible via the {@link java.lang.Object#getClass Object.getClass}
   76    * operation.  The programmer should not draw conclusions about a method handle
   77    * from its specific class, as the method handle class hierarchy (if any)
   78    * may change from time to time or across implementations from different vendors.
   79    *
   80    * <h3>Method handle compilation</h3>
   81    * A Java method call expression naming {@code invokeExact} or {@code invoke}
   82    * can invoke a method handle from Java source code.
   83    * From the viewpoint of source code, these methods can take any arguments
   84    * and their result can be cast to any return type.
   85    * Formally this is accomplished by giving the invoker methods
   86    * {@code Object} return types and variable arity {@code Object} arguments,
   87    * but they have an additional quality called <em>signature polymorphism</em>
   88    * which connects this freedom of invocation directly to the JVM execution stack.
   89    * <p>
   90    * As is usual with virtual methods, source-level calls to {@code invokeExact}
   91    * and {@code invoke} compile to an {@code invokevirtual} instruction.
   92    * More unusually, the compiler must record the actual argument types,
   93    * and may not perform method invocation conversions on the arguments.
   94    * Instead, it must push them on the stack according to their own unconverted types.
   95    * The method handle object itself is pushed on the stack before the arguments.
   96    * The compiler then calls the method handle with a symbolic type descriptor which
   97    * describes the argument and return types.
   98    * <p>
   99    * To issue a complete symbolic type descriptor, the compiler must also determine
  100    * the return type.  This is based on a cast on the method invocation expression,
  101    * if there is one, or else {@code Object} if the invocation is an expression
  102    * or else {@code void} if the invocation is a statement.
  103    * The cast may be to a primitive type (but not {@code void}).
  104    * <p>
  105    * As a corner case, an uncasted {@code null} argument is given
  106    * a symbolic type descriptor of {@code java.lang.Void}.
  107    * The ambiguity with the type {@code Void} is harmless, since there are no references of type
  108    * {@code Void} except the null reference.
  109    *
  110    * <h3>Method handle invocation</h3>
  111    * The first time a {@code invokevirtual} instruction is executed
  112    * it is linked, by symbolically resolving the names in the instruction
  113    * and verifying that the method call is statically legal.
  114    * This is true of calls to {@code invokeExact} and {@code invoke}.
  115    * In this case, the symbolic type descriptor emitted by the compiler is checked for
  116    * correct syntax and names it contains are resolved.
  117    * Thus, an {@code invokevirtual} instruction which invokes
  118    * a method handle will always link, as long
  119    * as the symbolic type descriptor is syntactically well-formed
  120    * and the types exist.
  121    * <p>
  122    * When the {@code invokevirtual} is executed after linking,
  123    * the receiving method handle's type is first checked by the JVM
  124    * to ensure that it matches the symbolic type descriptor.
  125    * If the type match fails, it means that the method which the
  126    * caller is invoking is not present on the individual
  127    * method handle being invoked.
  128    * <p>
  129    * In the case of {@code invokeExact}, the type descriptor of the invocation
  130    * (after resolving symbolic type names) must exactly match the method type
  131    * of the receiving method handle.
  132    * In the case of plain, inexact {@code invoke}, the resolved type descriptor
  133    * must be a valid argument to the receiver's {@link #asType asType} method.
  134    * Thus, plain {@code invoke} is more permissive than {@code invokeExact}.
  135    * <p>
  136    * After type matching, a call to {@code invokeExact} directly
  137    * and immediately invoke the method handle's underlying method
  138    * (or other behavior, as the case may be).
  139    * <p>
  140    * A call to plain {@code invoke} works the same as a call to
  141    * {@code invokeExact}, if the symbolic type descriptor specified by the caller
  142    * exactly matches the method handle's own type.
  143    * If there is a type mismatch, {@code invoke} attempts
  144    * to adjust the type of the receiving method handle,
  145    * as if by a call to {@link #asType asType},
  146    * to obtain an exactly invokable method handle {@code M2}.
  147    * This allows a more powerful negotiation of method type
  148    * between caller and callee.
  149    * <p>
  150    * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable,
  151    * and implementations are therefore not required to materialize it.)
  152    *
  153    * <h3>Invocation checking</h3>
  154    * In typical programs, method handle type matching will usually succeed.
  155    * But if a match fails, the JVM will throw a {@link WrongMethodTypeException},
  156    * either directly (in the case of {@code invokeExact}) or indirectly as if
  157    * by a failed call to {@code asType} (in the case of {@code invoke}).
  158    * <p>
  159    * Thus, a method type mismatch which might show up as a linkage error
  160    * in a statically typed program can show up as
  161    * a dynamic {@code WrongMethodTypeException}
  162    * in a program which uses method handles.
  163    * <p>
  164    * Because method types contain "live" {@code Class} objects,
  165    * method type matching takes into account both types names and class loaders.
  166    * Thus, even if a method handle {@code M} is created in one
  167    * class loader {@code L1} and used in another {@code L2},
  168    * method handle calls are type-safe, because the caller's symbolic type
  169    * descriptor, as resolved in {@code L2},
  170    * is matched against the original callee method's symbolic type descriptor,
  171    * as resolved in {@code L1}.
  172    * The resolution in {@code L1} happens when {@code M} is created
  173    * and its type is assigned, while the resolution in {@code L2} happens
  174    * when the {@code invokevirtual} instruction is linked.
  175    * <p>
  176    * Apart from the checking of type descriptors,
  177    * a method handle's capability to call its underlying method is unrestricted.
  178    * If a method handle is formed on a non-public method by a class
  179    * that has access to that method, the resulting handle can be used
  180    * in any place by any caller who receives a reference to it.
  181    * <p>
  182    * Unlike with the Core Reflection API, where access is checked every time
  183    * a reflective method is invoked,
  184    * method handle access checking is performed
  185    * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>.
  186    * In the case of {@code ldc} (see below), access checking is performed as part of linking
  187    * the constant pool entry underlying the constant method handle.
  188    * <p>
  189    * Thus, handles to non-public methods, or to methods in non-public classes,
  190    * should generally be kept secret.
  191    * They should not be passed to untrusted code unless their use from
  192    * the untrusted code would be harmless.
  193    *
  194    * <h3>Method handle creation</h3>
  195    * Java code can create a method handle that directly accesses
  196    * any method, constructor, or field that is accessible to that code.
  197    * This is done via a reflective, capability-based API called
  198    * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}
  199    * For example, a static method handle can be obtained
  200    * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}.
  201    * There are also conversion methods from Core Reflection API objects,
  202    * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
  203    * <p>
  204    * Like classes and strings, method handles that correspond to accessible
  205    * fields, methods, and constructors can also be represented directly
  206    * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes.
  207    * A new type of constant pool entry, {@code CONSTANT_MethodHandle},
  208    * refers directly to an associated {@code CONSTANT_Methodref},
  209    * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref}
  210    * constant pool entry.
  211    * (For more details on method handle constants,
  212    * see the <a href="package-summary.html#mhcon">package summary</a>.)
  213    * <p>
  214    * Method handles produced by lookups or constant loads from methods or
  215    * constructors with the variable arity modifier bit ({@code 0x0080})
  216    * have a corresponding variable arity, as if they were defined with
  217    * the help of {@link #asVarargsCollector asVarargsCollector}.
  218    * <p>
  219    * A method reference may refer either to a static or non-static method.
  220    * In the non-static case, the method handle type includes an explicit
  221    * receiver argument, prepended before any other arguments.
  222    * In the method handle's type, the initial receiver argument is typed
  223    * according to the class under which the method was initially requested.
  224    * (E.g., if a non-static method handle is obtained via {@code ldc},
  225    * the type of the receiver is the class named in the constant pool entry.)
  226    * <p>
  227    * When a method handle to a virtual method is invoked, the method is
  228    * always looked up in the receiver (that is, the first argument).
  229    * <p>
  230    * A non-virtual method handle to a specific virtual method implementation
  231    * can also be created.  These do not perform virtual lookup based on
  232    * receiver type.  Such a method handle simulates the effect of
  233    * an {@code invokespecial} instruction to the same method.
  234    *
  235    * <h3>Usage examples</h3>
  236    * Here are some examples of usage:
  237    * <p><blockquote><pre>
  238   Object x, y; String s; int i;
  239   MethodType mt; MethodHandle mh;
  240   MethodHandles.Lookup lookup = MethodHandles.lookup();
  241   // mt is (char,char)String
  242   mt = MethodType.methodType(String.class, char.class, char.class);
  243   mh = lookup.findVirtual(String.class, "replace", mt);
  244   s = (String) mh.invokeExact("daddy",'d','n');
  245   // invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
  246   assertEquals(s, "nanny");
  247   // weakly typed invocation (using MHs.invoke)
  248   s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
  249   assertEquals(s, "savvy");
  250   // mt is (Object[])List
  251   mt = MethodType.methodType(java.util.List.class, Object[].class);
  252   mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
  253   assert(mh.isVarargsCollector());
  254   x = mh.invoke("one", "two");
  255   // invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
  256   assertEquals(x, java.util.Arrays.asList("one","two"));
  257   // mt is (Object,Object,Object)Object
  258   mt = MethodType.genericMethodType(3);
  259   mh = mh.asType(mt);
  260   x = mh.invokeExact((Object)1, (Object)2, (Object)3);
  261   // invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
  262   assertEquals(x, java.util.Arrays.asList(1,2,3));
  263   // mt is ()int
  264   mt = MethodType.methodType(int.class);
  265   mh = lookup.findVirtual(java.util.List.class, "size", mt);
  266   i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
  267   // invokeExact(Ljava/util/List;)I
  268   assert(i == 3);
  269   mt = MethodType.methodType(void.class, String.class);
  270   mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
  271   mh.invokeExact(System.out, "Hello, world.");
  272   // invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
  273    * </pre></blockquote>
  274    * Each of the above calls to {@code invokeExact} or plain {@code invoke}
  275    * generates a single invokevirtual instruction with
  276    * the symbolic type descriptor indicated in the following comment.
  277    * In these examples, the helper method {@code assertEquals} is assumed to
  278    * be a method which calls {@link Objects.equals java.util.Objects#equals}
  279    * on its arguments, and asserts that the result is true.
  280    *
  281    * <h3>Exceptions</h3>
  282    * The methods {@code invokeExact} and {@code invoke} are declared
  283    * to throw {@link java.lang.Throwable Throwable},
  284    * which is to say that there is no static restriction on what a method handle
  285    * can throw.  Since the JVM does not distinguish between checked
  286    * and unchecked exceptions (other than by their class, of course),
  287    * there is no particular effect on bytecode shape from ascribing
  288    * checked exceptions to method handle invocations.  But in Java source
  289    * code, methods which perform method handle calls must either explicitly
  290    * throw {@code Throwable}, or else must catch all
  291    * throwables locally, rethrowing only those which are legal in the context,
  292    * and wrapping ones which are illegal.
  293    *
  294    * <h3><a name="sigpoly"></a>Signature polymorphism</h3>
  295    * The unusual compilation and linkage behavior of
  296    * {@code invokeExact} and plain {@code invoke}
  297    * is referenced by the term <em>signature polymorphism</em>.
  298    * As defined in the Java Language Specification,
  299    * a signature polymorphic method is one which can operate with
  300    * any of a wide range of call signatures and return types.
  301    * <p>
  302    * In source code, a call to a signature polymorphic method will
  303    * compile, regardless of the requested symbolic type descriptor.
  304    * As usual, the Java compiler emits an {@code invokevirtual}
  305    * instruction with the given symbolic type descriptor against the named method.
  306    * The unusual part is that the symbolic type descriptor is derived from
  307    * the actual argument and return types, not from the method declaration.
  308    * <p>
  309    * When the JVM processes bytecode containing signature polymorphic calls,
  310    * it will successfully link any such call, regardless of its symbolic type descriptor.
  311    * (In order to retain type safety, the JVM will guard such calls with suitable
  312    * dynamic type checks, as described elsewhere.)
  313    * <p>
  314    * Bytecode generators, including the compiler back end, are required to emit
  315    * untransformed symbolic type descriptors for these methods.
  316    * Tools which determine symbolic linkage are required to accept such
  317    * untransformed descriptors, without reporting linkage errors.
  318    *
  319    * <h3>Interoperation between method handles and the Core Reflection API</h3>
  320    * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API,
  321    * any class member represented by a Core Reflection API object
  322    * can be converted to a behaviorally equivalent method handle.
  323    * For example, a reflective {@link java.lang.reflect.Method Method} can
  324    * be converted to a method handle using
  325    * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
  326    * The resulting method handles generally provide more direct and efficient
  327    * access to the underlying class members.
  328    * <p>
  329    * As a special case,
  330    * when the Core Reflection API is used to view the signature polymorphic
  331    * methods {@code invokeExact} or plain {@code invoke} in this class,
  332    * they appear as ordinary non-polymorphic methods.
  333    * Their reflective appearance, as viewed by
  334    * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
  335    * is unaffected by their special status in this API.
  336    * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers}
  337    * will report exactly those modifier bits required for any similarly
  338    * declared method, including in this case {@code native} and {@code varargs} bits.
  339    * <p>
  340    * As with any reflected method, these methods (when reflected) may be
  341    * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.
  342    * However, such reflective calls do not result in method handle invocations.
  343    * Such a call, if passed the required argument
  344    * (a single one, of type {@code Object[]}), will ignore the argument and
  345    * will throw an {@code UnsupportedOperationException}.
  346    * <p>
  347    * Since {@code invokevirtual} instructions can natively
  348    * invoke method handles under any symbolic type descriptor, this reflective view conflicts
  349    * with the normal presentation of these methods via bytecodes.
  350    * Thus, these two native methods, when reflectively viewed by
  351    * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
  352    * <p>
  353    * In order to obtain an invoker method for a particular type descriptor,
  354    * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker},
  355    * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}.
  356    * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
  357    * API is also able to return a method handle
  358    * to call {@code invokeExact} or plain {@code invoke},
  359    * for any specified type descriptor .
  360    *
  361    * <h3>Interoperation between method handles and Java generics</h3>
  362    * A method handle can be obtained on a method, constructor, or field
  363    * which is declared with Java generic types.
  364    * As with the Core Reflection API, the type of the method handle
  365    * will constructed from the erasure of the source-level type.
  366    * When a method handle is invoked, the types of its arguments
  367    * or the return value cast type may be generic types or type instances.
  368    * If this occurs, the compiler will replace those
  369    * types by their erasures when it constructs the symbolic type descriptor
  370    * for the {@code invokevirtual} instruction.
  371    * <p>
  372    * Method handles do not represent
  373    * their function-like types in terms of Java parameterized (generic) types,
  374    * because there are three mismatches between function-like types and parameterized
  375    * Java types.
  376    * <ul>
  377    * <li>Method types range over all possible arities,
  378    * from no arguments to up to 255 of arguments (a limit imposed by the JVM).
  379    * Generics are not variadic, and so cannot represent this.</li>
  380    * <li>Method types can specify arguments of primitive types,
  381    * which Java generic types cannot range over.</li>
  382    * <li>Higher order functions over method handles (combinators) are
  383    * often generic across a wide range of function types, including
  384    * those of multiple arities.  It is impossible to represent such
  385    * genericity with a Java type parameter.</li>
  386    * </ul>
  387    *
  388    * @see MethodType
  389    * @see MethodHandles
  390    * @author John Rose, JSR 292 EG
  391    */
  392   public abstract class MethodHandle {
  393       // { JVM internals:
  394   
  395       private byte       vmentry;    // adapter stub or method entry point
  396       //private int      vmslots;    // optionally, hoist type.form.vmslots
  397       /*non-public*/ Object vmtarget;   // VM-specific, class-specific target value
  398   
  399       // TO DO:  vmtarget should be invisible to Java, since the JVM puts internal
  400       // managed pointers into it.  Making it visible exposes it to debuggers,
  401       // which can cause errors when they treat the pointer as an Object.
  402   
  403       // These two dummy fields are present to force 'I' and 'J' signatures
  404       // into this class's constant pool, so they can be transferred
  405       // to vmentry when this class is loaded.
  406       static final int  INT_FIELD = 0;
  407       static final long LONG_FIELD = 0;
  408   
  409       // vmentry (a void* field) is used *only* by the JVM.
  410       // The JVM adjusts its type to int or long depending on system wordsize.
  411       // Since it is statically typed as neither int nor long, it is impossible
  412       // to use this field from Java bytecode.  (Please don't try to, either.)
  413   
  414       // The vmentry is an assembly-language stub which is jumped to
  415       // immediately after the method type is verified.
  416       // For a direct MH, this stub loads the vmtarget's entry point
  417       // and jumps to it.
  418   
  419       // } End of JVM internals.
  420   
  421       static { MethodHandleImpl.initStatics(); }
  422   
  423       // interface MethodHandle<R throws X extends Exception,A...>
  424       // { MethodType<R throws X,A...> type(); public R invokeExact(A...) throws X; }
  425   
  426       /**
  427        * Internal marker interface which distinguishes (to the Java compiler)
  428        * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>.
  429        */
  430       @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
  431       @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
  432       @interface PolymorphicSignature { }
  433   
  434       private MethodType type;
  435   
  436       /**
  437        * Reports the type of this method handle.
  438        * Every invocation of this method handle via {@code invokeExact} must exactly match this type.
  439        * @return the method handle type
  440        */
  441       public MethodType type() {
  442           return type;
  443       }
  444   
  445       /**
  446        * Package-private constructor for the method handle implementation hierarchy.
  447        * Method handle inheritance will be contained completely within
  448        * the {@code java.lang.invoke} package.
  449        */
  450       // @param type type (permanently assigned) of the new method handle
  451       /*non-public*/ MethodHandle(MethodType type) {
  452           type.getClass();  // elicit NPE
  453           this.type = type;
  454       }
  455   
  456       /**
  457        * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match.
  458        * The symbolic type descriptor at the call site of {@code invokeExact} must
  459        * exactly match this method handle's {@link #type type}.
  460        * No conversions are allowed on arguments or return values.
  461        * <p>
  462        * When this method is observed via the Core Reflection API,
  463        * it will appear as a single native method, taking an object array and returning an object.
  464        * If this native method is invoked directly via
  465        * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
  466        * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
  467        * it will throw an {@code UnsupportedOperationException}.
  468        * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor
  469        * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
  470        */
  471       public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
  472   
  473       /**
  474        * Invokes the method handle, allowing any caller type descriptor,
  475        * and optionally performing conversions on arguments and return values.
  476        * <p>
  477        * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type},
  478        * the call proceeds as if by {@link #invokeExact invokeExact}.
  479        * <p>
  480        * Otherwise, the call proceeds as if this method handle were first
  481        * adjusted by calling {@link #asType asType} to adjust this method handle
  482        * to the required type, and then the call proceeds as if by
  483        * {@link #invokeExact invokeExact} on the adjusted method handle.
  484        * <p>
  485        * There is no guarantee that the {@code asType} call is actually made.
  486        * If the JVM can predict the results of making the call, it may perform
  487        * adaptations directly on the caller's arguments,
  488        * and call the target method handle according to its own exact type.
  489        * <p>
  490        * The resolved type descriptor at the call site of {@code invoke} must
  491        * be a valid argument to the receivers {@code asType} method.
  492        * In particular, the caller must specify the same argument arity
  493        * as the callee's type,
  494        * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
  495        * <p>
  496        * When this method is observed via the Core Reflection API,
  497        * it will appear as a single native method, taking an object array and returning an object.
  498        * If this native method is invoked directly via
  499        * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
  500        * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
  501        * it will throw an {@code UnsupportedOperationException}.
  502        * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor
  503        * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
  504        * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
  505        */
  506       public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;
  507   
  508       /**
  509        * Performs a variable arity invocation, passing the arguments in the given array
  510        * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
  511        * which mentions only the type {@code Object}, and whose arity is the length
  512        * of the argument array.
  513        * <p>
  514        * Specifically, execution proceeds as if by the following steps,
  515        * although the methods are not guaranteed to be called if the JVM
  516        * can predict their effects.
  517        * <ul>
  518        * <li>Determine the length of the argument array as {@code N}.
  519        *     For a null reference, {@code N=0}. </li>
  520        * <li>Determine the general type {@code TN} of {@code N} arguments as
  521        *     as {@code TN=MethodType.genericMethodType(N)}.</li>
  522        * <li>Force the original target method handle {@code MH0} to the
  523        *     required type, as {@code MH1 = MH0.asType(TN)}. </li>
  524        * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li>
  525        * <li>Invoke the type-adjusted method handle on the unpacked arguments:
  526        *     MH1.invokeExact(A0, ...). </li>
  527        * <li>Take the return value as an {@code Object} reference. </li>
  528        * </ul>
  529        * <p>
  530        * Because of the action of the {@code asType} step, the following argument
  531        * conversions are applied as necessary:
  532        * <ul>
  533        * <li>reference casting
  534        * <li>unboxing
  535        * <li>widening primitive conversions
  536        * </ul>
  537        * <p>
  538        * The result returned by the call is boxed if it is a primitive,
  539        * or forced to null if the return type is void.
  540        * <p>
  541        * This call is equivalent to the following code:
  542        * <p><blockquote><pre>
  543        * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0);
  544        * Object result = invoker.invokeExact(this, arguments);
  545        * </pre></blockquote>
  546        * <p>
  547        * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke},
  548        * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI.
  549        * It can therefore be used as a bridge between native or reflective code and method handles.
  550        *
  551        * @param arguments the arguments to pass to the target
  552        * @return the result returned by the target
  553        * @throws ClassCastException if an argument cannot be converted by reference casting
  554        * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
  555        * @throws Throwable anything thrown by the target method invocation
  556        * @see MethodHandles#spreadInvoker
  557        */
  558       public Object invokeWithArguments(Object... arguments) throws Throwable {
  559           int argc = arguments == null ? 0 : arguments.length;
  560           MethodType type = type();
  561           if (type.parameterCount() != argc || isVarargsCollector()) {
  562               // simulate invoke
  563               return asType(MethodType.genericMethodType(argc)).invokeWithArguments(arguments);
  564           }
  565           MethodHandle invoker = type.invokers().varargsInvoker();
  566           return invoker.invokeExact(this, arguments);
  567       }
  568   
  569       /**
  570        * Performs a variable arity invocation, passing the arguments in the given array
  571        * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
  572        * which mentions only the type {@code Object}, and whose arity is the length
  573        * of the argument array.
  574        * <p>
  575        * This method is also equivalent to the following code:
  576        * <p><blockquote><pre>
  577        * {@link #invokeWithArguments(Object...) invokeWithArguments}(arguments.toArray())
  578        * </pre></blockquote>
  579        *
  580        * @param arguments the arguments to pass to the target
  581        * @return the result returned by the target
  582        * @throws NullPointerException if {@code arguments} is a null reference
  583        * @throws ClassCastException if an argument cannot be converted by reference casting
  584        * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
  585        * @throws Throwable anything thrown by the target method invocation
  586        */
  587       public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable {
  588           return invokeWithArguments(arguments.toArray());
  589       }
  590   
  591       /**
  592        * Produces an adapter method handle which adapts the type of the
  593        * current method handle to a new type.
  594        * The resulting method handle is guaranteed to report a type
  595        * which is equal to the desired new type.
  596        * <p>
  597        * If the original type and new type are equal, returns {@code this}.
  598        * <p>
  599        * The new method handle, when invoked, will perform the following
  600        * steps:
  601        * <ul>
  602        * <li>Convert the incoming argument list to match the original
  603        *     method handle's argument list.
  604        * <li>Invoke the original method handle on the converted argument list.
  605        * <li>Convert any result returned by the original method handle
  606        *     to the return type of new method handle.
  607        * </ul>
  608        * <p>
  609        * This method provides the crucial behavioral difference between
  610        * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}.
  611        * The two methods
  612        * perform the same steps when the caller's type descriptor exactly m atches
  613        * the callee's, but when the types differ, plain {@link #invoke invoke}
  614        * also calls {@code asType} (or some internal equivalent) in order
  615        * to match up the caller's and callee's types.
  616        * <p>
  617        * If the current method is a variable arity method handle
  618        * argument list conversion may involve the conversion and collection
  619        * of several arguments into an array, as
  620        * {@linkplain #asVarargsCollector described elsewhere}.
  621        * In every other case, all conversions are applied <em>pairwise</em>,
  622        * which means that each argument or return value is converted to
  623        * exactly one argument or return value (or no return value).
  624        * The applied conversions are defined by consulting the
  625        * the corresponding component types of the old and new
  626        * method handle types.
  627        * <p>
  628        * Let <em>T0</em> and <em>T1</em> be corresponding new and old parameter types,
  629        * or old and new return types.  Specifically, for some valid index {@code i}, let
  630        * <em>T0</em>{@code =newType.parameterType(i)} and <em>T1</em>{@code =this.type().parameterType(i)}.
  631        * Or else, going the other way for return values, let
  632        * <em>T0</em>{@code =this.type().returnType()} and <em>T1</em>{@code =newType.returnType()}.
  633        * If the types are the same, the new method handle makes no change
  634        * to the corresponding argument or return value (if any).
  635        * Otherwise, one of the following conversions is applied
  636        * if possible:
  637        * <ul>
  638        * <li>If <em>T0</em> and <em>T1</em> are references, then a cast to <em>T1</em> is applied.
  639        *     (The types do not need to be related in any particular way.
  640        *     This is because a dynamic value of null can convert to any reference type.)
  641        * <li>If <em>T0</em> and <em>T1</em> are primitives, then a Java method invocation
  642        *     conversion (JLS 5.3) is applied, if one exists.
  643        *     (Specifically, <em>T0</em> must convert to <em>T1</em> by a widening primitive conversion.)
  644        * <li>If <em>T0</em> is a primitive and <em>T1</em> a reference,
  645        *     a Java casting conversion (JLS 5.5) is applied if one exists.
  646        *     (Specifically, the value is boxed from <em>T0</em> to its wrapper class,
  647        *     which is then widened as needed to <em>T1</em>.)
  648        * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
  649        *     conversion will be applied at runtime, possibly followed
  650        *     by a Java method invocation conversion (JLS 5.3)
  651        *     on the primitive value.  (These are the primitive widening conversions.)
  652        *     <em>T0</em> must be a wrapper class or a supertype of one.
  653        *     (In the case where <em>T0</em> is Object, these are the conversions
  654        *     allowed by {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.)
  655        *     The unboxing conversion must have a possibility of success, which means that
  656        *     if <em>T0</em> is not itself a wrapper class, there must exist at least one
  657        *     wrapper class <em>TW</em> which is a subtype of <em>T0</em> and whose unboxed
  658        *     primitive value can be widened to <em>T1</em>.
  659        * <li>If the return type <em>T1</em> is marked as void, any returned value is discarded
  660        * <li>If the return type <em>T0</em> is void and <em>T1</em> a reference, a null value is introduced.
  661        * <li>If the return type <em>T0</em> is void and <em>T1</em> a primitive,
  662        *     a zero value is introduced.
  663        * </ul>
  664       * (<em>Note:</em> Both <em>T0</em> and <em>T1</em> may be regarded as static types,
  665        * because neither corresponds specifically to the <em>dynamic type</em> of any
  666        * actual argument or return value.)
  667        * <p>
  668        * The method handle conversion cannot be made if any one of the required
  669        * pairwise conversions cannot be made.
  670        * <p>
  671        * At runtime, the conversions applied to reference arguments
  672        * or return values may require additional runtime checks which can fail.
  673        * An unboxing operation may fail because the original reference is null,
  674        * causing a {@link java.lang.NullPointerException NullPointerException}.
  675        * An unboxing operation or a reference cast may also fail on a reference
  676        * to an object of the wrong type,
  677        * causing a {@link java.lang.ClassCastException ClassCastException}.
  678        * Although an unboxing operation may accept several kinds of wrappers,
  679        * if none are available, a {@code ClassCastException} will be thrown.
  680        *
  681        * @param newType the expected type of the new method handle
  682        * @return a method handle which delegates to {@code this} after performing
  683        *           any necessary argument conversions, and arranges for any
  684        *           necessary return value conversions
  685        * @throws NullPointerException if {@code newType} is a null reference
  686        * @throws WrongMethodTypeException if the conversion cannot be made
  687        * @see MethodHandles#explicitCastArguments
  688        */
  689       public MethodHandle asType(MethodType newType) {
  690           if (!type.isConvertibleTo(newType)) {
  691               throw new WrongMethodTypeException("cannot convert "+this+" to "+newType);
  692           }
  693           return MethodHandleImpl.convertArguments(this, newType, 1);
  694       }
  695   
  696       /**
  697        * Makes an <em>array-spreading</em> method handle, which accepts a trailing array argument
  698        * and spreads its elements as positional arguments.
  699        * The new method handle adapts, as its <i>target</i>,
  700        * the current method handle.  The type of the adapter will be
  701        * the same as the type of the target, except that the final
  702        * {@code arrayLength} parameters of the target's type are replaced
  703        * by a single array parameter of type {@code arrayType}.
  704        * <p>
  705        * If the array element type differs from any of the corresponding
  706        * argument types on the original target,
  707        * the original target is adapted to take the array elements directly,
  708        * as if by a call to {@link #asType asType}.
  709        * <p>
  710        * When called, the adapter replaces a trailing array argument
  711        * by the array's elements, each as its own argument to the target.
  712        * (The order of the arguments is preserved.)
  713        * They are converted pairwise by casting and/or unboxing
  714        * to the types of the trailing parameters of the target.
  715        * Finally the target is called.
  716        * What the target eventually returns is returned unchanged by the adapter.
  717        * <p>
  718        * Before calling the target, the adapter verifies that the array
  719        * contains exactly enough elements to provide a correct argument count
  720        * to the target method handle.
  721        * (The array may also be null when zero elements are required.)
  722        * <p>
  723        * Here are some simple examples of array-spreading method handles:
  724        * <blockquote><pre>
  725   MethodHandle equals = publicLookup()
  726     .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
  727   assert( (boolean) equals.invokeExact("me", (Object)"me"));
  728   assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
  729   // spread both arguments from a 2-array:
  730   MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
  731   assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
  732   assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
  733   // spread both arguments from a String array:
  734   MethodHandle eq2s = equals.asSpreader(String[].class, 2);
  735   assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
  736   assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
  737   // spread second arguments from a 1-array:
  738   MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
  739   assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
  740   assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
  741   // spread no arguments from a 0-array or null:
  742   MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
  743   assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
  744   assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
  745   // asSpreader and asCollector are approximate inverses:
  746   for (int n = 0; n <= 2; n++) {
  747       for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
  748           MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
  749           assert( (boolean) equals2.invokeWithArguments("me", "me"));
  750           assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
  751       }
  752   }
  753   MethodHandle caToString = publicLookup()
  754     .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
  755   assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
  756   MethodHandle caString3 = caToString.asCollector(char[].class, 3);
  757   assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
  758   MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
  759   assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
  760        * </pre></blockquote>
  761        * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
  762        * @param arrayLength the number of arguments to spread from an incoming array argument
  763        * @return a new method handle which spreads its final array argument,
  764        *         before calling the original method handle
  765        * @throws NullPointerException if {@code arrayType} is a null reference
  766        * @throws IllegalArgumentException if {@code arrayType} is not an array type
  767        * @throws IllegalArgumentException if target does not have at least
  768        *         {@code arrayLength} parameter types,
  769        *         or if {@code arrayLength} is negative
  770        * @throws WrongMethodTypeException if the implied {@code asType} call fails
  771        * @see #asCollector
  772        */
  773       public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) {
  774           asSpreaderChecks(arrayType, arrayLength);
  775           return MethodHandleImpl.spreadArguments(this, arrayType, arrayLength);
  776       }
  777   
  778       private void asSpreaderChecks(Class<?> arrayType, int arrayLength) {
  779           spreadArrayChecks(arrayType, arrayLength);
  780           int nargs = type().parameterCount();
  781           if (nargs < arrayLength || arrayLength < 0)
  782               throw newIllegalArgumentException("bad spread array length");
  783           if (arrayType != Object[].class && arrayLength != 0) {
  784               boolean sawProblem = false;
  785               Class<?> arrayElement = arrayType.getComponentType();
  786               for (int i = nargs - arrayLength; i < nargs; i++) {
  787                   if (!MethodType.canConvert(arrayElement, type().parameterType(i))) {
  788                       sawProblem = true;
  789                       break;
  790                   }
  791               }
  792               if (sawProblem) {
  793                   ArrayList<Class<?>> ptypes = new ArrayList<Class<?>>(type().parameterList());
  794                   for (int i = nargs - arrayLength; i < nargs; i++) {
  795                       ptypes.set(i, arrayElement);
  796                   }
  797                   // elicit an error:
  798                   this.asType(MethodType.methodType(type().returnType(), ptypes));
  799               }
  800           }
  801       }
  802   
  803       private void spreadArrayChecks(Class<?> arrayType, int arrayLength) {
  804           Class<?> arrayElement = arrayType.getComponentType();
  805           if (arrayElement == null)
  806               throw newIllegalArgumentException("not an array type", arrayType);
  807           if ((arrayLength & 0x7F) != arrayLength) {
  808               if ((arrayLength & 0xFF) != arrayLength)
  809                   throw newIllegalArgumentException("array length is not legal", arrayLength);
  810               assert(arrayLength >= 128);
  811               if (arrayElement == long.class ||
  812                   arrayElement == double.class)
  813                   throw newIllegalArgumentException("array length is not legal for long[] or double[]", arrayLength);
  814           }
  815       }
  816   
  817       /**
  818        * Makes an <em>array-collecting</em> method handle, which accepts a given number of trailing
  819        * positional arguments and collects them into an array argument.
  820        * The new method handle adapts, as its <i>target</i>,
  821        * the current method handle.  The type of the adapter will be
  822        * the same as the type of the target, except that a single trailing
  823        * parameter (usually of type {@code arrayType}) is replaced by
  824        * {@code arrayLength} parameters whose type is element type of {@code arrayType}.
  825        * <p>
  826        * If the array type differs from the final argument type on the original target,
  827        * the original target is adapted to take the array type directly,
  828        * as if by a call to {@link #asType asType}.
  829        * <p>
  830        * When called, the adapter replaces its trailing {@code arrayLength}
  831        * arguments by a single new array of type {@code arrayType}, whose elements
  832        * comprise (in order) the replaced arguments.
  833        * Finally the target is called.
  834        * What the target eventually returns is returned unchanged by the adapter.
  835        * <p>
  836        * (The array may also be a shared constant when {@code arrayLength} is zero.)
  837        * <p>
  838        * (<em>Note:</em> The {@code arrayType} is often identical to the last
  839        * parameter type of the original target.
  840        * It is an explicit argument for symmetry with {@code asSpreader}, and also
  841        * to allow the target to use a simple {@code Object} as its last parameter type.)
  842        * <p>
  843        * In order to create a collecting adapter which is not restricted to a particular
  844        * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead.
  845        * <p>
  846        * Here are some examples of array-collecting method handles:
  847        * <blockquote><pre>
  848   MethodHandle deepToString = publicLookup()
  849     .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
  850   assertEquals("[won]",   (String) deepToString.invokeExact(new Object[]{"won"}));
  851   MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
  852   assertEquals(methodType(String.class, Object.class), ts1.type());
  853   //assertEquals("[won]", (String) ts1.invokeExact(         new Object[]{"won"})); //FAIL
  854   assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
  855   // arrayType can be a subtype of Object[]
  856   MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
  857   assertEquals(methodType(String.class, String.class, String.class), ts2.type());
  858   assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
  859   MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
  860   assertEquals("[]", (String) ts0.invokeExact());
  861   // collectors can be nested, Lisp-style
  862   MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
  863   assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
  864   // arrayType can be any primitive array type
  865   MethodHandle bytesToString = publicLookup()
  866     .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
  867     .asCollector(byte[].class, 3);
  868   assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
  869   MethodHandle longsToString = publicLookup()
  870     .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
  871     .asCollector(long[].class, 1);
  872   assertEquals("[123]", (String) longsToString.invokeExact((long)123));
  873        * </pre></blockquote>
  874        * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
  875        * @param arrayLength the number of arguments to collect into a new array argument
  876        * @return a new method handle which collects some trailing argument
  877        *         into an array, before calling the original method handle
  878        * @throws NullPointerException if {@code arrayType} is a null reference
  879        * @throws IllegalArgumentException if {@code arrayType} is not an array type
  880        *         or {@code arrayType} is not assignable to this method handle's trailing parameter type,
  881        *         or {@code arrayLength} is not a legal array size
  882        * @throws WrongMethodTypeException if the implied {@code asType} call fails
  883        * @see #asSpreader
  884        * @see #asVarargsCollector
  885        */
  886       public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
  887           asCollectorChecks(arrayType, arrayLength);
  888           MethodHandle collector = ValueConversions.varargsArray(arrayType, arrayLength);
  889           return MethodHandleImpl.collectArguments(this, type.parameterCount()-1, collector);
  890       }
  891   
  892       // private API: return true if last param exactly matches arrayType
  893       private boolean asCollectorChecks(Class<?> arrayType, int arrayLength) {
  894           spreadArrayChecks(arrayType, arrayLength);
  895           int nargs = type().parameterCount();
  896           if (nargs != 0) {
  897               Class<?> lastParam = type().parameterType(nargs-1);
  898               if (lastParam == arrayType)  return true;
  899               if (lastParam.isAssignableFrom(arrayType))  return false;
  900           }
  901           throw newIllegalArgumentException("array type not assignable to trailing argument", this, arrayType);
  902       }
  903   
  904       /**
  905        * Makes a <em>variable arity</em> adapter which is able to accept
  906        * any number of trailing positional arguments and collect them
  907        * into an array argument.
  908        * <p>
  909        * The type and behavior of the adapter will be the same as
  910        * the type and behavior of the target, except that certain
  911        * {@code invoke} and {@code asType} requests can lead to
  912        * trailing positional arguments being collected into target's
  913        * trailing parameter.
  914        * Also, the last parameter type of the adapter will be
  915        * {@code arrayType}, even if the target has a different
  916        * last parameter type.
  917        * <p>
  918        * This transformation may return {@code this} if the method handle is
  919        * already of variable arity and its trailing parameter type
  920        * is identical to {@code arrayType}.
  921        * <p>
  922        * When called with {@link #invokeExact invokeExact}, the adapter invokes
  923        * the target with no argument changes.
  924        * (<em>Note:</em> This behavior is different from a
  925        * {@linkplain #asCollector fixed arity collector},
  926        * since it accepts a whole array of indeterminate length,
  927        * rather than a fixed number of arguments.)
  928        * <p>
  929        * When called with plain, inexact {@link #invoke invoke}, if the caller
  930        * type is the same as the adapter, the adapter invokes the target as with
  931        * {@code invokeExact}.
  932        * (This is the normal behavior for {@code invoke} when types match.)
  933        * <p>
  934        * Otherwise, if the caller and adapter arity are the same, and the
  935        * trailing parameter type of the caller is a reference type identical to
  936        * or assignable to the trailing parameter type of the adapter,
  937        * the arguments and return values are converted pairwise,
  938        * as if by {@link #asType asType} on a fixed arity
  939        * method handle.
  940        * <p>
  941        * Otherwise, the arities differ, or the adapter's trailing parameter
  942        * type is not assignable from the corresponding caller type.
  943        * In this case, the adapter replaces all trailing arguments from
  944        * the original trailing argument position onward, by
  945        * a new array of type {@code arrayType}, whose elements
  946        * comprise (in order) the replaced arguments.
  947        * <p>
  948        * The caller type must provides as least enough arguments,
  949        * and of the correct type, to satisfy the target's requirement for
  950        * positional arguments before the trailing array argument.
  951        * Thus, the caller must supply, at a minimum, {@code N-1} arguments,
  952        * where {@code N} is the arity of the target.
  953        * Also, there must exist conversions from the incoming arguments
  954        * to the target's arguments.
  955        * As with other uses of plain {@code invoke}, if these basic
  956        * requirements are not fulfilled, a {@code WrongMethodTypeException}
  957        * may be thrown.
  958        * <p>
  959        * In all cases, what the target eventually returns is returned unchanged by the adapter.
  960        * <p>
  961        * In the final case, it is exactly as if the target method handle were
  962        * temporarily adapted with a {@linkplain #asCollector fixed arity collector}
  963        * to the arity required by the caller type.
  964        * (As with {@code asCollector}, if the array length is zero,
  965        * a shared constant may be used instead of a new array.
  966        * If the implied call to {@code asCollector} would throw
  967        * an {@code IllegalArgumentException} or {@code WrongMethodTypeException},
  968        * the call to the variable arity adapter must throw
  969        * {@code WrongMethodTypeException}.)
  970        * <p>
  971        * The behavior of {@link #asType asType} is also specialized for
  972        * variable arity adapters, to maintain the invariant that
  973        * plain, inexact {@code invoke} is always equivalent to an {@code asType}
  974        * call to adjust the target type, followed by {@code invokeExact}.
  975        * Therefore, a variable arity adapter responds
  976        * to an {@code asType} request by building a fixed arity collector,
  977        * if and only if the adapter and requested type differ either
  978        * in arity or trailing argument type.
  979        * The resulting fixed arity collector has its type further adjusted
  980        * (if necessary) to the requested type by pairwise conversion,
  981        * as if by another application of {@code asType}.
  982        * <p>
  983        * When a method handle is obtained by executing an {@code ldc} instruction
  984        * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked
  985        * as a variable arity method (with the modifier bit {@code 0x0080}),
  986        * the method handle will accept multiple arities, as if the method handle
  987        * constant were created by means of a call to {@code asVarargsCollector}.
  988        * <p>
  989        * In order to create a collecting adapter which collects a predetermined
  990        * number of arguments, and whose type reflects this predetermined number,
  991        * use {@link #asCollector asCollector} instead.
  992        * <p>
  993        * No method handle transformations produce new method handles with
  994        * variable arity, unless they are documented as doing so.
  995        * Therefore, besides {@code asVarargsCollector},
  996        * all methods in {@code MethodHandle} and {@code MethodHandles}
  997        * will return a method handle with fixed arity,
  998        * except in the cases where they are specified to return their original
  999        * operand (e.g., {@code asType} of the method handle's own type).
 1000        * <p>
 1001        * Calling {@code asVarargsCollector} on a method handle which is already
 1002        * of variable arity will produce a method handle with the same type and behavior.
 1003        * It may (or may not) return the original variable arity method handle.
 1004        * <p>
 1005        * Here is an example, of a list-making variable arity method handle:
 1006        * <blockquote><pre>
 1007   MethodHandle deepToString = publicLookup()
 1008     .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
 1009   MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
 1010   assertEquals("[won]",   (String) ts1.invokeExact(    new Object[]{"won"}));
 1011   assertEquals("[won]",   (String) ts1.invoke(         new Object[]{"won"}));
 1012   assertEquals("[won]",   (String) ts1.invoke(                      "won" ));
 1013   assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
 1014   // findStatic of Arrays.asList(...) produces a variable arity method handle:
 1015   MethodHandle asList = publicLookup()
 1016     .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
 1017   assertEquals(methodType(List.class, Object[].class), asList.type());
 1018   assert(asList.isVarargsCollector());
 1019   assertEquals("[]", asList.invoke().toString());
 1020   assertEquals("[1]", asList.invoke(1).toString());
 1021   assertEquals("[two, too]", asList.invoke("two", "too").toString());
 1022   String[] argv = { "three", "thee", "tee" };
 1023   assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
 1024   assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
 1025   List ls = (List) asList.invoke((Object)argv);
 1026   assertEquals(1, ls.size());
 1027   assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
 1028        * </pre></blockquote>
 1029        * <p style="font-size:smaller;">
 1030        * <em>Discussion:</em>
 1031        * These rules are designed as a dynamically-typed variation
 1032        * of the Java rules for variable arity methods.
 1033        * In both cases, callers to a variable arity method or method handle
 1034        * can either pass zero or more positional arguments, or else pass
 1035        * pre-collected arrays of any length.  Users should be aware of the
 1036        * special role of the final argument, and of the effect of a
 1037        * type match on that final argument, which determines whether
 1038        * or not a single trailing argument is interpreted as a whole
 1039        * array or a single element of an array to be collected.
 1040        * Note that the dynamic type of the trailing argument has no
 1041        * effect on this decision, only a comparison between the symbolic
 1042        * type descriptor of the call site and the type descriptor of the method handle.)
 1043        *
 1044        * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
 1045        * @return a new method handle which can collect any number of trailing arguments
 1046        *         into an array, before calling the original method handle
 1047        * @throws NullPointerException if {@code arrayType} is a null reference
 1048        * @throws IllegalArgumentException if {@code arrayType} is not an array type
 1049        *         or {@code arrayType} is not assignable to this method handle's trailing parameter type
 1050        * @see #asCollector
 1051        * @see #isVarargsCollector
 1052        * @see #asFixedArity
 1053        */
 1054       public MethodHandle asVarargsCollector(Class<?> arrayType) {
 1055           Class<?> arrayElement = arrayType.getComponentType();
 1056           boolean lastMatch = asCollectorChecks(arrayType, 0);
 1057           if (isVarargsCollector() && lastMatch)
 1058               return this;
 1059           return AdapterMethodHandle.makeVarargsCollector(this, arrayType);
 1060       }
 1061   
 1062       /**
 1063        * Determines if this method handle
 1064        * supports {@linkplain #asVarargsCollector variable arity} calls.
 1065        * Such method handles arise from the following sources:
 1066        * <ul>
 1067        * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector}
 1068        * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method}
 1069        *     which resolves to a variable arity Java method or constructor
 1070        * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle}
 1071        *     which resolves to a variable arity Java method or constructor
 1072        * </ul>
 1073        * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls
 1074        * @see #asVarargsCollector
 1075        * @see #asFixedArity
 1076        */
 1077       public boolean isVarargsCollector() {
 1078           return false;
 1079       }
 1080   
 1081       /**
 1082        * Makes a <em>fixed arity</em> method handle which is otherwise
 1083        * equivalent to the the current method handle.
 1084        * <p>
 1085        * If the current method handle is not of
 1086        * {@linkplain #asVarargsCollector variable arity},
 1087        * the current method handle is returned.
 1088        * This is true even if the current method handle
 1089        * could not be a valid input to {@code asVarargsCollector}.
 1090        * <p>
 1091        * Otherwise, the resulting fixed-arity method handle has the same
 1092        * type and behavior of the current method handle,
 1093        * except that {@link #isVarargsCollector isVarargsCollector}
 1094        * will be false.
 1095        * The fixed-arity method handle may (or may not) be the
 1096        * a previous argument to {@code asVarargsCollector}.
 1097        * <p>
 1098        * Here is an example, of a list-making variable arity method handle:
 1099        * <blockquote><pre>
 1100   MethodHandle asListVar = publicLookup()
 1101     .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
 1102     .asVarargsCollector(Object[].class);
 1103   MethodHandle asListFix = asListVar.asFixedArity();
 1104   assertEquals("[1]", asListVar.invoke(1).toString());
 1105   Exception caught = null;
 1106   try { asListFix.invoke((Object)1); }
 1107   catch (Exception ex) { caught = ex; }
 1108   assert(caught instanceof ClassCastException);
 1109   assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
 1110   try { asListFix.invoke("two", "too"); }
 1111   catch (Exception ex) { caught = ex; }
 1112   assert(caught instanceof WrongMethodTypeException);
 1113   Object[] argv = { "three", "thee", "tee" };
 1114   assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
 1115   assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
 1116   assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
 1117   assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
 1118        * </pre></blockquote>
 1119        *
 1120        * @return a new method handle which accepts only a fixed number of arguments
 1121        * @see #asVarargsCollector
 1122        * @see #isVarargsCollector
 1123        */
 1124       public MethodHandle asFixedArity() {
 1125           assert(!isVarargsCollector());
 1126           return this;
 1127       }
 1128   
 1129       /**
 1130        * Binds a value {@code x} to the first argument of a method handle, without invoking it.
 1131        * The new method handle adapts, as its <i>target</i>,
 1132        * the current method handle by binding it to the given argument.
 1133        * The type of the bound handle will be
 1134        * the same as the type of the target, except that a single leading
 1135        * reference parameter will be omitted.
 1136        * <p>
 1137        * When called, the bound handle inserts the given value {@code x}
 1138        * as a new leading argument to the target.  The other arguments are
 1139        * also passed unchanged.
 1140        * What the target eventually returns is returned unchanged by the bound handle.
 1141        * <p>
 1142        * The reference {@code x} must be convertible to the first parameter
 1143        * type of the target.
 1144        * <p>
 1145        * (<em>Note:</em>  Because method handles are immutable, the target method handle
 1146        * retains its original type and behavior.)
 1147        * @param x  the value to bind to the first argument of the target
 1148        * @return a new method handle which prepends the given value to the incoming
 1149        *         argument list, before calling the original method handle
 1150        * @throws IllegalArgumentException if the target does not have a
 1151        *         leading parameter type that is a reference type
 1152        * @throws ClassCastException if {@code x} cannot be converted
 1153        *         to the leading parameter type of the target
 1154        * @see MethodHandles#insertArguments
 1155        */
 1156       public MethodHandle bindTo(Object x) {
 1157           Class<?> ptype;
 1158           if (type().parameterCount() == 0 ||
 1159               (ptype = type().parameterType(0)).isPrimitive())
 1160               throw newIllegalArgumentException("no leading reference parameter", x);
 1161           x = MethodHandles.checkValue(ptype, x);
 1162           // Cf. MethodHandles.insertArguments for the following logic:
 1163           MethodHandle bmh = MethodHandleImpl.bindReceiver(this, x);
 1164           if (bmh != null)  return bmh;
 1165           return MethodHandleImpl.bindArgument(this, 0, x);
 1166       }
 1167   
 1168       /**
 1169        * Returns a string representation of the method handle,
 1170        * starting with the string {@code "MethodHandle"} and
 1171        * ending with the string representation of the method handle's type.
 1172        * In other words, this method returns a string equal to the value of:
 1173        * <blockquote><pre>
 1174        * "MethodHandle" + type().toString()
 1175        * </pre></blockquote>
 1176        * <p>
 1177        * (<em>Note:</em>  Future releases of this API may add further information
 1178        * to the string representation.
 1179        * Therefore, the present syntax should not be parsed by applications.)
 1180        *
 1181        * @return a string representation of the method handle
 1182        */
 1183       @Override
 1184       public String toString() {
 1185           if (DEBUG_METHOD_HANDLE_NAMES)  return debugString();
 1186           return "MethodHandle"+type;
 1187       }
 1188   
 1189       /*non-public*/
 1190       String debugString() {
 1191           return getNameString(this);
 1192       }
 1193   }

Home » openjdk-7 » java.lang.invoke » [javadoc | source]