如何告诉方法有一个使用反射的varargs参数? [英] How to tell a method has a varargs argument using reflection?

查看:118
本文介绍了如何告诉方法有一个使用反射的varargs参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是示例代码

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数组。

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

在反射库中是否有任何意思我可以告诉该方法最初声明采取varargs?

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?

是的。 java .lang.reflect.Method.isVarArgs()

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

但是,如果您尝试以人类可读的形式组装和显示方法签名,则仅可使用此选项。如果需要使用反射调用varargs方法,则必须将varargs参数组装成数组类型的参数。

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参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆