在数组中的参数时调用Method.invoke()

编程入门 行业动态 更新时间:2024-10-14 22:16:08
本文介绍了在数组中的参数时调用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()

本文发布于:2023-08-04 09:11:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1294999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时调   组中   参数   invoke   Method

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!