Is there any way to distinguish these two methods when using reflection to invoke it?
public void method(Object[] args) {}
public void method(Object... args) {}
Is there any way to distinguish these two methods when using reflection to invoke it?
public void method(Object[] args) {}
public void method(Object... args) {}
You can test if a Parameter
is a varargs parameter via Parameter#isVarArgs()
.
Returns
true
if this parameter represents a variable argument list; returnsfalse
otherwise.
The Executable
interface has a similar method, which both Constructor
and Method
implement.
Returns
true
if this executable was declared to take a variable number of arguments; returnsfalse
otherwise.
However, if I correctly understand why you're asking this question, knowing this information won't help you. Whether or not the parameter is varargs doesn't affect how you would call Method#invoke
. As mentioned by GhostCat and hinted at by Ferrybig, you'll need to pass an array (as a single argument) either way. See this question for some examples.
A distinct non answer: it doesn't matter for reflection. Both methods expect an array of Object to be passed as argument.
When both methods are used the exact same way in reflection, why would it matter if the source code said "array" or "varargs"?! You see, when information isn't necessary for what you need to do, then it is a good thing to not care about that detail.
Beyond that: obviously a compiler needs to be able to distinguish the two methods, so the information is available in the class file. But for reflection, as said, it does not matter. Therefore it would not surprise me if you can't use reflection to distinguish between a method expecting an array and one expecting a vararg.