在数组中的参数时调用Method.invoke() [英] Call Method.invoke() when arguments in array

查看:166
本文介绍了在数组中的参数时调用Method.invoke()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下界面:

interface Foo {
  void bar(String a, int b);
}

我想调用 Foo.bar (在Foo的实现上)反思性地。 但是,参数在数组中,我不知道它的大小。

I want to invoke Foo.bar (on an implementation of Foo) reflectively. However, the arguments are in array and i do not know the size of it.

以下不起作用:

void gee(Foo someFoo, Method bar, Object[] args) {
  bar.invoke(someFoo, args);
}

这不起作用,因为 args 由编译器作为单个参数进行威胁,并且数组不会扩展为vararg,而是在一个包含单个元素的数组中(内部)包装,即

That does not work because args is threated by the compiler as a single argument and the array is not "expanded" to vararg but is wrapped (internally) in one more array with single element, i.e.

@Test
public void varArgTest() {
  assertTrue(varArgFoo(new Object[] {1, 2}) == 1);
}

private static <T> int varArgFoo(T... arg) {
    return arg.length;
}

如何调用 Method.invoke()在这种情况下,以便将数组作为vararg进行威胁?

或者更一般的问题:当参数在数组中时如何调用vararg方法我不知道数据的大小数组直到运行时。

How can i call Method.invoke() in this case so that the array is threated as vararg?
Or more general question: how do i call vararg method when arguments are in array i do not knew the size of the array until runtime.

推荐答案


以下不起作用:

The following does not work:

是的。


这不起作用,因为args受到威胁编译器作为
单个参数,并且数组没有扩展到vararg,而是在另一个包含单个元素的数组中包含(内部)
,即

That does not work because args is threated by the compiler as a single argument and the array is not "expanded" to vararg but is wrapped (internally) in one more array with single element, i.e.

使用您提供的代码,数组的元素应该成为varargs参数。如果你没有这样做,要么你没有显示你的实际代码,要么出现其他错误。

With the code you have presented, the array's elements should become the varargs arguments. If that's not happening for you, either you are not showing your actual code, or something else is wrong.

如果你的 args 变量没有数组类型(例如,它是键入的 Object ),那么可能会发生这种情况。但这不是你要显示的代码。

If somehow your args variable does not have an array type (e.g. it is typed Object), then that could happen. But that is not the code you're showing.

或者如果你有一些附加参数你没有显示(例如你试图做像 bar.invoke(someFoo,firstArg,args); ,然后它不会扩展 args ,因为你正在使用这个方法已经形成了varargs。

Or if you have some "additional" arguments you are not showing (e.g. you are trying to do something like bar.invoke(someFoo, firstArg, args);, then it will not expand args, because you are using the method in the varargs form already.

这篇关于在数组中的参数时调用Method.invoke()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆