IllegalArgumentException When You Call the Invoke Method Using Java Reflections

advertisements

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 value object you pass into invoke is not an instance of the class on which the method 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 of com.xxx.Currency - which of course it isn't, because it's a List.)

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 call

method.invoke(obj, value)

instead of your current single one-arg call.