Java 的 MethodHandle.invokeExact(Object...args) 采用可变长度的参数列表。但是,当我尝试传递 Object [] 数组而不是列表时,出现错误。见下文:
private void doIt() throws Throwable {
Method meth = Foo.class.getDeclaredMethods()[0];
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle mh = lookup.unreflect(meth);
Foo foo = new Foo();
String myStr = "aaa";
Integer myInt = new Integer(10);
Object [] myArray = {foo, myStr, myInt};
mh.invokeExact(foo, myStr, myInt); // prints "Called aaa 10"
mh.invokeExact(myArray); // throws Exception
}
class Foo {
public void bar(String myStr, Integer myInt) {
System.out.println("Called " + myStr + " " + myInt);
}
}
第二次调用 invokeExact() 产生此异常:
Exception in thread "main" java.lang.invoke.WrongMethodTypeException: (Ljava/lang/String;Ljava/lang/Integer;)V cannot be called with a different arity as ([Ljava/lang/Object;)V
at io.rhubarb.core.TestInvoke.doIt0(TestInvoke.java:26)
at io.rhubarb.core.TestInvoke.main(TestInvoke.java:11)
这可能与两年前修复的 Eclipse 中的错误有关(https://bugs.eclipse.org/bugs/show_bug.cgi?id=385404)但我不这么认为,因为当我关闭 Eclipse 时,删除 /target 目录,使用 Maven 重新编译所有内容,然后从命令行运行我得到相同的结果。
我正在使用 Eclipse Kepler SR2,一切都是最新的,以及 JDK 1.7.0_25。