How to say that a method has a varargs argument using reflection?

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

Output signal

 public void org.example.TestRef.testA(java.lang.String[]) 

So, the method signature is reported to take an array of String.

Is there any average value in the reflection library, can I say that the method was originally declared to accept varargs?

+6
java variadic-functions
source share
2 answers

Is there any average value in the reflection library, can I say that the method was originally declared to accept varargs?

Yeah. java.lang.reflect.Method.isVarArgs() .

However, this is useful if you are trying to collect and display method signatures in a readable form. If you need to call the varargs method using reflection, you will have to collect the varargs arguments into an argument with an array.

+18
source share

no difference

 static public void main(String[] args) static public void main(String... args) 

actually ... the notation was introduced very late in the process of adding vararg to java. James Gosling suggested this, he thinks it's cute. Until then, [] stands for vararg.

+1
source share

All Articles