Java – how to use reflection to tell a method to have a varargs parameter?
•
Java
This 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 is
public void org.example.TestRef.testA(java.lang.String[])
Therefore, the signature of the method is reported in a string array
Is there any meaning in the reflection library that I can tell that the method was originally declared to adopt varargs?
Solution
yes. java. lang.reflect. Method. isVarArgs().
However, if you try to assemble and display method signatures in human readable form, use this option only If you need to call the varargs method using reflection, you must assemble the varargs parameter into an array type parameter
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码