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
This means that the
valueobject you pass intoinvokeis not an instance of the class on which themethodis 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.