Java – method. Java is called when a parameter in an array invoke()

I have the following interfaces:

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

I want to call foo reflexively Bar (on the implementation of foo) However, the parameter is in the array, and I don't know its size

The following do not work:

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

This does not work because args is threatened by the compiler as a single parameter, and the array is not "extended" to vararg, but wrapped (internally) in an array containing a 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;
}

In this case, how to call method Invoke() to threaten the array as vararg? Or a more general question: how do I call the vararg method when the parameter is in the array? I don't know the size of the array until runtime

Solution

Yes, it does

Using the code you provided, the elements of the array should become varargs parameters If you do not, either you do not display your actual code, or other errors occur

This can happen if your args variable has no array type in some way (for example, it is a typed object) But this is not the code you want to show

Or, if you have some "additional" parameters that you do not display (for example, you are trying to do something like bar. Invoke (somefoo, firstarg, args); Then it will not extend args, because the method form you are using varargs has been changed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>