使用 Java Reflections 调用 invoke 方法时出现 IllegalArgumentException
我有一个具有如下方法的类:-
public void setCurrencyCode(List<String> newCurrencycode){
this.currencycode = newCurrencycode;
}
我正在使用 Java Relections 来调用此方法,如下所示:-
try {
List<String> value = new ArrayList<String>();
value.add("GB");
Class<?> clazz = Class.forName( "com.xxx.Currency" );
Object obj = clazz.newInstance();
Class param[] = { List.class };
Method method = obj.getClass().getDeclaredMethod( "setCurrencyCode", param );
method.invoke( value );
} catch(Exception e) {
System.out.println( "Exception : " + e.getMessage() );
}
但是,“调用”调用时引发异常:- java.lang.IllegalArgumentException:对象不是声明类的实例
有什么想法吗?
谢谢莎拉
I have a class that has a method as follows :-
public void setCurrencyCode(List<String> newCurrencycode){
this.currencycode = newCurrencycode;
}
I am using Java Relections to invoke this method as follows :-
try {
List<String> value = new ArrayList<String>();
value.add("GB");
Class<?> clazz = Class.forName( "com.xxx.Currency" );
Object obj = clazz.newInstance();
Class param[] = { List.class };
Method method = obj.getClass().getDeclaredMethod( "setCurrencyCode", param );
method.invoke( value );
} catch(Exception e) {
System.out.println( "Exception : " + e.getMessage() );
}
However, an exception is raised on the "invoke" call :-
java.lang.IllegalArgumentException: object is not an instance of declaring class
Any ideas?
Thanks
Sarah
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有调用 invoke() 正确:
invoke()
期望目标对象作为第一个参数,然后是方法调用的参数作为以下参数(因为 java 1.5,它是一个 varargs 参数)试试这个:
You are not calling invoke() correctly:
invoke()
expects the target object as the first parameter, then the parameters to the method call as the following parameters (since java 1.5, it's a varargs parameter)Try this:
这意味着您传递给
invoke
的value
对象不是定义method
的类的实例。这是因为 invoke 的第一个参数是要调用的对象,后续参数是被调用方法的参数。 (在这种情况下,值看起来需要是com.xxx.Currency
的实例 - 当然它不是,因为它是一个List
。) '正在调用一个非静态方法(并且会遇到创建新实例的麻烦),然后在 try 块结束时调用 obj.setCurrencyCode(value) 的反射等效方法' d 需要打电话
代替您当前的单身单参数调用。
This means that the
value
object you pass intoinvoke
is not an instance of the class on which themethod
is defined. This is because the first argument of invoke is the object on which to make the call, and the subsequent arguments are the parameters to the invoked method. (In this case it looks like value needs to be an instance ofcom.xxx.Currency
- which of course it isn't, because it's aList
.)Since you're calling a non-static method (and going to to trouble of creating a new instance), then for the reflective equivalent of
obj.setCurrencyCode(value)
, at the end of your try block you'd need to callinstead of your current single one-arg call.