IllegalArgumentException when calling a call method using Java Reflections

I have a class that has the following method: -

public void setCurrencyCode(List<String> newCurrencycode){ this.currencycode = newCurrencycode; } 

I use Java Relections to call 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 thrown when invoke is called: java.lang.IllegalArgumentException: the object is not an instance of the declaration class

Any ideas?

thanks

Sarah

+4
source share
2 answers

This means that the value object you pass to invoke is not an instance of the class for which method is defined. This is because the first argument to invoke is the object for which you want to make a call, and the subsequent arguments are parameters of the called method. (In this case, it looks like the value should be an instance of com.xxx.Currency - this is certainly not the case, because it is a List .)

Since you are calling a non-static method (and are going to create problems with creating a new instance), for the reflective equivalent of obj.setCurrencyCode(value) at the end of your try block, you will need to call

 method.invoke(obj, value) 

instead of your current single call to one-arg.

+6
source

You are not calling invoke () correctly: invoke() expects the target to be first, and then the method call parameters as the following parameters (since java 1.5, this is the varargs parameter)

Try the following:

 try { List<String> value = new ArrayList<String>(); value.add("GB"); Class<?> clazz = Class.forName( "com.xxx.Currency" ); Object obj = clazz.newInstance(); // Since java 1.5, you don't need Class[] for params: it a varargs now Method method = clazz.getDeclaredMethod( "setCurrencyCode", List.class ); // you already have a reference to the class - no need for obj.getClass() method.invoke( obj, value ); // invoke expects the target object, then the parameters } catch(Exception e) { System.out.println( "Exception : " + e.getMessage() ); } } 
+7
source

All Articles