如何使用反射在java中调用带有变量参数的方法? [英] How to invoke method with variable arguments in java using reflection?

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

问题描述

我正在尝试使用java反射调用带有变量参数的方法。这是托管方法的类:

I'm trying to invoke a method with variable arguments using java reflection. Here's the class which hosts the method:

public class TestClass {

public void setParam(N ... n){
    System.out.println("Calling set param...");
}

这是调用代码:

try {
        Class<?> c = Class.forName("com.test.reflection.TestClass");
        Method  method = c.getMethod ("setParam", com.test.reflection.N[].class);
        method.invoke(c, new com.test.reflection.N[]{});

我在最后一行以错误的参数数量的形式收到IllegalArgumentException在调用invoke。不知道我做错了什么。

I'm getting IllegalArgumentException in the form of "wrong number of arguments" at the last line where I'm calling invoke. Not sure what I'm doing wrong.

任何指针都会受到赞赏。

Any pointers will be appreciated.


  • 谢谢

推荐答案

public class Test {

public void setParam(N... n) {
    System.out.println("Calling set param...");
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws Exception {
    Test t=new Test();
    Class<?> c = Class.forName("test.Test");
    Method  method = c.getMethod ("setParam", N[].class);
    method.invoke(t, (Object) new N[]{});
}
}

适用于我。


  1. 在实例上抛出你的N []到对象

  2. 调用调用,而不是在类

这篇关于如何使用反射在java中调用带有变量参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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