[英]Unable to invoke the method with variable arguments using reflection in java
[英]How to invoke method with variable arguments in java using reflection?
我正在尝试使用java反射调用带有变量参数的方法。 这是承载方法的类:
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[]{});
我在调用invoke的最后一行以“错误的参数数量”的形式得到IllegalArgumentException。 不知道我做错了什么。
任何指针将不胜感激。
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[]{});
}
}
适合我。
您的代码段中没有调用methd的TestClass
实例。 您需要TestClass
一个实例 ,而不仅仅是TestClass
本身。 在c
上调用newInstance()
,并使用此调用的结果作为method.invoke()
的第一个参数。
此外,为了确保您的数组被视为一个参数,而不是varargs,您需要将其强制转换为Object:
m.invoke(testClassInstance, (Object) new com.test.reflection.N[]{});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.