How to tell a method has a varargs argument using reflection?

天大地大妈咪最大 提交于 2019-12-10 04:10:09

问题


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?


回答1:


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.




回答2:


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. James Gosling proposed it, he thinks it's cuter. Before that, the same [] denotes the vararg.



来源:https://stackoverflow.com/questions/3042050/how-to-tell-a-method-has-a-varargs-argument-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!