如何使用反射在java中调用带有可变参数的方法?
我正在尝试使用 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[]{});
在调用调用的最后一行,我收到了“参数数量错误”形式的 IllegalArgumentException。不确定我做错了什么。
任何指示将不胜感激。
- 谢谢
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...");
}
Here's the invoking code :
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[]{});
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.
- Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我有用。
Works for me.
您的代码片段中没有调用该方法的
TestClass
实例。您需要TestClass
的实例,而不仅仅是TestClass
本身。在c
上调用newInstance()
,并使用此调用的结果作为method.invoke()
的第一个参数。此外,为了确保您的数组被视为一个参数,而不是可变参数,您需要将其转换为 Object:
There is no
TestClass
instance in your code snippet on which the methd is invoked. You need an instance of theTestClass
, and not just theTestClass
itself. CallnewInstance()
onc
, and use the result of this call as the first argument ofmethod.invoke()
.Moreover, to make sure your array is considered as one argument, and not a varargs, you need to cast it to Object: