Call Method.invoke() when arguments in array

折月煮酒 提交于 2019-12-01 21:04:35

The following does not work:

Yes it does.

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.

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.

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.

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.

A vararg parameter is actually an array parameter with a bit of extra metadata. So when you use Method.invoke, you need to wrap the array in another array:

Object[] varargs = new Object[] { 10, 20 };
Object argumentArray = new Object[] { varargs };
method.invoke(target, argumentArray);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!