无法通过反射调用具有可变参数的方法 - NoSuchMethodException [英] Can't invoke method with varargs parameters with reflection - NoSuchMethodException

查看:41
本文介绍了无法通过反射调用具有可变参数的方法 - NoSuchMethodException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用反射来调用带有可变参数的方法.

I'm trying to use reflection to invoke method with varargs parameters.

并捕获NoSuchMethodException.我无法弄清楚这里出了什么问题.

And caught NoSuchMethodException. I couldn't figure out what is wrong here.

代码:

public class ReflectionTest {

    public ReflectionTest() {   }

    private void varargMethod(String string, Integer ... var) {

        System.out.println("vargarMethod() called");
        System.out.println(string + " Number of args: " + var.length
                + "\nContents");

        for (int i = 0; i < var.length; i++) {
            System.out.printf(" args %d: %d", i, var[i]);
            //System.out.println(" args " + i + ": " + var[i]);
        }

        System.out.println();
    }

    public static void main(String[] args) throws Exception {

        Class[] parameterTypes = new Class[] { String.class, int.class, int.class, int.class };

        //System.out.println(Arrays.toString(parameterTypes));

        Method varMeth = test.getClass().getDeclaredMethod("varargMethod", parameterTypes);
        System.out.println("varMeth" + varMeth);

        Object[] arguments = new Object[] { new String("my perfect string"),
                new Integer(10), new Integer(100), new Integer(47) };

        varMeth.invoke(test, arguments);

它准确地抛出:

java.lang.NoSuchMethodException: ReflectionTest.varargMethod(java.lang.String, int, int, int)

java.lang.NoSuchMethodException: ReflectionTest.varargMethod(java.lang.String, int, int, int)

  • 如何解决这个问题?
  • 推荐答案

    对于可变参数,参数类型应该是 Integer[].class 因为可变参数表达式指定参数是可变数组参数.所以正确的方法是:

    The parameter types should be Integer[].class for a varargs as varargs expression specifies that the parameter is a variable array parameter. So a correct way is:

    Class[] parameterTypes = new Class[] { String.class, Integer[].class };
    
    //System.out.println(Arrays.toString(parameterTypes));
    ReflectionTest test = new ReflectionTest();
    Method varMeth = test.getClass().getDeclaredMethod("varargMethod", 
                                                          parameterTypes);
    System.out.println("varMeth" + varMeth);
    
    Object[] arguments = new Object[] { new String("my perfect string"),
                                        new Integer[]{10, 100, 47}
                                      };
    
    varMeth.invoke(test, arguments);
    

    这篇关于无法通过反射调用具有可变参数的方法 - NoSuchMethodException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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