/* * Copyright 2008-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package java.dyn; //import sun.dyn.*; import sun.dyn.Access; import sun.dyn.MethodHandleImpl; import static java.dyn.MethodHandles.invokers; // package-private API import static sun.dyn.MemberName.newIllegalArgumentException; // utility /** * A method handle is a typed reference to the entry point of a method. *
* Method handles are strongly typed according to signature. * They are not distinguished by method name or enclosing class. * A method handle must be invoked under a signature which exactly matches * the method handle's own type. *
* Every method handle confesses its type via the type accessor.
* The structure of this type is a series of classes, one of which is
* the return type of the method (or void.class if none).
*
* Every method handle appears as an object containing a method named
* invoke, whose signature exactly matches
* the method handle's type.
* A Java method call expression, which compiles to an
* invokevirtual instruction,
* can invoke this method from Java source code.
*
* Every call to a method handle specifies an intended method type,
* which must exactly match the type of the method handle.
* (The type is specified in the invokevirtual instruction,
* via a {@code CONSTANT_NameAndType} constant pool entry.)
* The call looks within the receiver object for a method
* named invoke of the intended method type.
* The call fails with a {@link WrongMethodTypeException}
* if the method does not exist, even if there is an invoke
* method of a closely similar signature.
* As with other kinds
* of methods in the JVM, signature matching during method linkage
* is exact, and does not allow for language-level implicit conversions
* such as {@code String} to {@code Object} or {@code short} to {@code int}.
*
* A method handle is an unrestricted capability to call a method. * A method handle can be formed on a non-public method by a class * that has access to that method; the resulting handle can be used * in any place by any caller who receives a reference to it. Thus, access * checking is performed when the method handle is created, not * (as in reflection) every time it is called. Handles to non-public * methods, or in non-public classes, should generally be kept secret. * They should not be passed to untrusted code. *
* Bytecode in an extended JVM can directly call a method handle's
* invoke from an invokevirtual instruction.
* The receiver class type must be MethodHandle and the method name
* must be invoke. The signature of the invocation
* (after resolving symbolic type names) must exactly match the method type
* of the target method.
*
* Every invoke method always throws {@link Exception},
* which is to say that there is no static restriction on what a method handle
* can throw. Since the JVM does not distinguish between checked
* and unchecked exceptions (other than by their class, of course),
* there is no particular effect on bytecode shape from ascribing
* checked exceptions to method handle invocations. But in Java source
* code, methods which perform method handle calls must either explicitly
* throw {@code Exception}, or else must catch all checked exceptions locally.
*
* Bytecode in an extended JVM can directly obtain a method handle
* for any accessible method from a ldc instruction
* which refers to a CONSTANT_Methodref or
* CONSTANT_InterfaceMethodref constant pool entry.
*
* All JVMs can also use a reflective API called MethodHandles
* for creating and calling method handles.
*
* A method reference may refer either to a static or non-static method.
* In the non-static case, the method handle type includes an explicit
* receiver argument, prepended before any other arguments.
* In the method handle's type, the initial receiver argument is typed
* according to the class under which the method was initially requested.
* (E.g., if a non-static method handle is obtained via ldc,
* the type of the receiver is the class named in the constant pool entry.)
*
* When a method handle to a virtual method is invoked, the method is * always looked up in the receiver (that is, the first argument). *
* A non-virtual method handles to a specific virtual method implementation
* can also be created. These do not perform virtual lookup based on
* receiver type. Such a method handle simulates the effect of
* an invokespecial instruction to the same method.
*
* Here are some examples of usage: *
* Object x, y; String s; int i;
* MethodType mt; MethodHandle mh;
* MethodHandles.Lookup lookup = MethodHandles.lookup();
* // mt is {(char,char) => String}
* mt = MethodType.make(String.class, char.class, char.class);
* mh = lookup.findVirtual(String.class, "replace", mt);
* // (Ljava/lang/String;CC)Ljava/lang/String;
* s = mh.<String>invoke("daddy",'d','n');
* assert(s.equals("nanny"));
* // weakly typed invocation (using MHs.invoke)
* s = (String) MethodHandles.invoke(mh, "sappy", 'p', 'v');
* assert(s.equals("savvy"));
* // mt is {Object[] => List}
* mt = MethodType.make(java.util.List.class, Object[].class);
* mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
* // mt is {(Object,Object,Object) => Object}
* mt = MethodType.makeGeneric(3);
* mh = MethodHandles.collectArguments(mh, mt);
* // mt is {(Object,Object,Object) => Object}
* // (Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
* x = mh.invoke((Object)1, (Object)2, (Object)3);
* assert(x.equals(java.util.Arrays.asList(1,2,3)));
* // mt is { => int}
* mt = MethodType.make(int.class);
* mh = lookup.findVirtual(java.util.List.class, "size", mt);
* // (Ljava/util/List;)I
* i = mh.<int>invoke(java.util.Arrays.asList(1,2,3));
* assert(i == 3);
*
* Each of the above calls generates a single invokevirtual instruction
* with the name {@code invoke} and the type descriptors indicated in the comments.
* The argument types are taken directly from the actual arguments,
* while the return type is taken from the type parameter.
* (This type parameter may be a primitive, and it defaults to {@code Object}.)
* * A note on generic typing: Method handles do not represent * their function types in terms of Java parameterized (generic) types, * because there are three mismatches between function types and parameterized * Java types. *
* The length of the arguments array must equal the parameter count * of the target's type. * The arguments array is spread into separate arguments. *
* In order to match the type of the target, the following argument * conversions are applied as necessary: *
* This call is equivalent to the following code: *
* MethodHandle invoker = MethodHandles.genericInvoker(this.type(), 0, true);
* Object result = invoker.invoke(this, arguments);
*
* @param arguments the arguments to pass to the target
* @return the result returned by the target
* @see MethodHandles#genericInvoker
*/
public final Object invokeVarargs(Object[] arguments) throws Throwable {
int argc = arguments == null ? 0 : arguments.length;
MethodType type = type();
if (argc <= 10) {
MethodHandle invoker = MethodHandles.invokers(type).genericInvoker();
switch (argc) {
case 0: return invoker.invoke(this);
case 1: return invoker.invoke(this,
arguments[0]);
case 2: return invoker.invoke(this,
arguments[0], arguments[1]);
case 3: return invoker.invoke(this,
arguments[0], arguments[1], arguments[2]);
case 4: return invoker.invoke(this,
arguments[0], arguments[1], arguments[2],
arguments[3]);
case 5: return invoker.invoke(this,
arguments[0], arguments[1], arguments[2],
arguments[3], arguments[4]);
case 6: return invoker.invoke(this,
arguments[0], arguments[1], arguments[2],
arguments[3], arguments[4], arguments[5]);
case 7: return invoker.invoke(this,
arguments[0], arguments[1], arguments[2],
arguments[3], arguments[4], arguments[5],
arguments[6]);
case 8: return invoker.invoke(this,
arguments[0], arguments[1], arguments[2],
arguments[3], arguments[4], arguments[5],
arguments[6], arguments[7]);
case 9: return invoker.invoke(this,
arguments[0], arguments[1], arguments[2],
arguments[3], arguments[4], arguments[5],
arguments[6], arguments[7], arguments[8]);
case 10: return invoker.invoke(this,
arguments[0], arguments[1], arguments[2],
arguments[3], arguments[4], arguments[5],
arguments[6], arguments[7], arguments[8],
arguments[9]);
}
}
// more than ten arguments get boxed in a varargs list:
MethodHandle invoker = MethodHandles.invokers(type).varargsInvoker(0);
return invoker.invoke(this, arguments);
}
/** Equivalent to {@code invokeVarargs(arguments.toArray())}. */
public final Object invokeVarargs(java.util.List> arguments) throws Throwable {
return invokeVarargs(arguments.toArray());
}
/* --- this is intentionally NOT a javadoc yet ---
* PROVISIONAL API, WORK IN PROGRESS:
* Produce an adapter method handle which adapts the type of the
* current method handle to a new type by pairwise argument conversion.
* The original type and new type must have the same number of arguments.
* The resulting method handle is guaranteed to confess a type
* which is equal to the desired new type.
* * If the original type and new type are equal, returns {@code this}. *
* The following conversions are applied as needed both to * arguments and return types. Let T0 and T1 be the differing * new and old parameter types (or old and new return types) * for corresponding values passed by the new and old method types. * Given those types T0, T1, one of the following conversions is applied * if possible: *
*/ /** * PROVISIONAL API, WORK IN PROGRESS: * Produce an adapter method handle which adapts the type of the * current method handle to a new type by pairwise argument conversion. * The original type and new type must have the same number of arguments. * The resulting method handle is guaranteed to confess a type * which is equal to the desired new type. *
* If the original type and new type are equal, returns {@code this}. *
* This method is equivalent to {@link MethodHandles#convertArguments}. * @param newType the expected type of the new method handle * @return a method handle which delegates to {@code this} after performing * any necessary argument conversions, and arranges for any * necessary return value conversions * @throws IllegalArgumentException if the conversion cannot be made * @see MethodHandles#convertArguments */ public final MethodHandle asType(MethodType newType) { return MethodHandles.convertArguments(this, newType); } /** * PROVISIONAL API, WORK IN PROGRESS: * Produce a method handle which adapts, as its target, * the current method handle. The type of the adapter will be * the same as the type of the target, except that all but the first * {@code keepPosArgs} parameters of the target's type are replaced * by a single array parameter of type {@code Object[]}. * Thus, if {@code keepPosArgs} is zero, the adapter will take all * arguments in a single object array. *
* When called, the adapter replaces a trailing array argument * by the array's elements, each as its own argument to the target. * (The order of the arguments is preserved.) * They are converted pairwise by casting and/or unboxing * (as if by {@link MethodHandles#convertArguments}) * to the types of the trailing parameters of the target. * Finally the target is called. * What the target eventually returns is returned unchanged by the adapter. *
* Before calling the target, the adapter verifies that the array * contains exactly enough elements to provide a correct argument count * to the target method handle. * (The array may also be null when zero elements are required.) * @param keepPosArgs the number of leading positional arguments to preserve * @return a new method handle which spreads its final argument, * before calling the original method handle * @throws IllegalArgumentException if target does not have at least * {@code keepPosArgs} parameter types */ public final MethodHandle asSpreader(int keepPosArgs) { MethodType oldType = type(); int nargs = oldType.parameterCount(); MethodType newType = oldType.dropParameterTypes(keepPosArgs, nargs); newType = newType.insertParameterTypes(keepPosArgs, Object[].class); return MethodHandles.spreadArguments(this, newType); } /** * PROVISIONAL API, WORK IN PROGRESS: * Produce a method handle which adapts, as its target, * the current method handle. The type of the adapter will be * the same as the type of the target, except that a single trailing * array parameter of type {@code Object[]} is replaced by * {@code spreadArrayArgs} parameters of type {@code Object}. *
* When called, the adapter replaces its trailing {@code spreadArrayArgs} * arguments by a single new {@code Object} array, whose elements * comprise (in order) the replaced arguments. * Finally the target is called. * What the target eventually returns is returned unchanged by the adapter. *
* (The array may also be a shared constant when {@code spreadArrayArgs} is zero.) * @param spreadArrayArgs the number of arguments to spread from the trailing array * @return a new method handle which collects some trailing argument * into an array, before calling the original method handle * @throws IllegalArgumentException if the last argument of the target * is not {@code Object[]} * @throws IllegalArgumentException if {@code spreadArrayArgs} is not * a legal array size * @deprecated Provisional and unstable; use {@link MethodHandles#collectArguments}. */ public final MethodHandle asCollector(int spreadArrayArgs) { MethodType oldType = type(); int nargs = oldType.parameterCount(); MethodType newType = oldType.dropParameterTypes(nargs-1, nargs); newType = newType.insertParameterTypes(nargs-1, MethodType.genericMethodType(spreadArrayArgs).parameterArray()); return MethodHandles.collectArguments(this, newType); } /** * PROVISIONAL API, WORK IN PROGRESS: * Produce a method handle which binds the given argument * to the current method handle as target. * The type of the bound handle will be * the same as the type of the target, except that a single leading * reference parameter will be omitted. *
* When called, the bound handle inserts the given value {@code x} * as a new leading argument to the target. The other arguments are * also passed unchanged. * What the target eventually returns is returned unchanged by the bound handle. *
* The reference {@code x} must be convertible to the first parameter * type of the target. * @param x the value to bind to the first argument of the target * @return a new method handle which collects some trailing argument * into an array, before calling the original method handle * @throws IllegalArgumentException if the target does not have a * leading parameter type that is a reference type * @throws ClassCastException if {@code x} cannot be converted * to the leading parameter type of the target * @deprecated Provisional and unstable; use {@link MethodHandles#insertArguments}. */ public final MethodHandle bindTo(Object x) { return MethodHandles.insertArguments(this, 0, x); } }