简体   繁体   English

如何告诉方法有一个使用反射的varargs参数?

[英]How to tell 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);
                        }
                }
        }
}

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. 因此,报告该方法的签名采用String数组。

Is there any mean in the reflection library I can tell that the method is originally declared to take a varargs? 在反射库中是否有任何意思我可以告诉该方法最初被声明为采用varargs?

Is there any mean in the reflection library I can tell that the method is originally declared to take a varargs? 在反射库中是否有任何意思我可以告诉该方法最初被声明为采用varargs?

Yup. 对。 java.lang.reflect.Method.isVarArgs() . 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. 如果需要使用反射调用varargs方法,则必须将varargs参数组装成数组类型的参数。

there is really 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 in java. 实际上......符号是在java中添加vararg的过程中很晚才引入的。 James Gosling proposed it, he thinks it's cuter. 詹姆斯戈斯林提出了这个问题,他认为这是可爱的。 Before that, the same [] denotes the vararg. 在此之前,相同的[]表示vararg。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM