Here is a sample code
package org.example;
import java.lang.reflect.Method;
class TestRef {
public void testA(String ... a) {
for (String i : a) {
System.out.println(i);
}
}
public static void main(String[] args){
Class testRefClass = TestRef.class;
for (Method m: testRefClass.getMethods()) {
if (m.getName() == "testA") {
System.out.println(m);
}
}
}
}
The output is
public void org.example.TestRef.testA(java.lang.String[])
So the signature of the method is reported to take a array of String.
Is there any mean in the reflection library I can tell that the method is originally declared to take a varargs?
Is there any mean in the reflection library I can tell that the method is originally declared to take a varargs?
Yup. java.lang.reflect.Method.isVarArgs()
.
However, this is only of use if you are trying to assemble and display method signatures in human readable form. If you need to invoke a varargs method using reflection, you will have to assemble the varargs arguments into an array-typed argument.
I should note that this section your example is questionable:
if (m.getName() == "testA") {
System.out.println(m);
}
In general, you shouldn't use ==
to test for String equality; see How do I compare strings in Java?.
Assuming the ==
test is actually working in your example, that must be because the JVM has "interned" the string that represents the method's name. While it is not unexpected, nothing (AFAIK) specifies that this will occur, so it is conceivable that your example won't work across all JVM implementations.