这是一个示例代码
- 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);
- }
- }
- }
- }
输出是
- public void org.example.TestRef.testA(java.lang.String[])
因此,报告该方法的签名采用String数组.
在反射库中是否有任何意思我可以告诉该方法最初被声明为采用varargs?
解决方法
Is there any mean in the reflection library I can tell that the method is originally declared to take a varargs?
对. java.lang.reflect.Method.isVarArgs()
.
但是,如果您尝试以人类可读的形式组装和显示方法签名,则仅使用此选项.如果需要使用反射调用varargs方法,则必须将varargs参数组装成数组类型的参数.