You need to call the method like this:
s.invoke(this, new Object[]{new Object[]{"hi", "there"}});
(... or use the alternative in @Jon's answer.)
The reason your current code fails is to do with the way that varadic methods are implemented in Java. Essentially, T1 xxx(T2... args)
is syntactic sugar for T1 xxx(T2[] args)
. And when you call the methods, xxx(arg1, arg2, arg3)
is syntactic sugar for xxx(new T2[]{arg1, arg2, arg3})
.
In this case, you are trying to call a varadic method using another varadic method with the same array basetype, and there are multiple possible interpretations of the code.
When there are two possible interpretations of a varadic call, Java assumes that you are trying to use the "unsugared" version of the call instead of the "sugared" version. Or to be more precise, the "sugared" interpretation is used if and only if:
- the number of actual arguments is not equal to the number of formal parameters, or
- the last actual argument is NOT assignment compatible with the (array) type of the last formal parameter.
If you are interested, this behaviour is specified in the JLS in section 15.12.4.2.
So ... my solution works by forcing the non-varadic interpretation and explicitly constructing the required array. @Jon's solution works by forcing the correct varadic interpretation.