Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Method.invoke() when arguments in array

I have the following interface:

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

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.

The following does not work:

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

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;
}

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.

like image 252
Op De Cirkel Avatar asked Feb 28 '26 11:02

Op De Cirkel


1 Answers

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);
like image 65
Jon Skeet Avatar answered Mar 01 '26 23:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!