Hi,
How can I invoke a method with parameters using reflections?
I want to the values to those parameters. Can somebody help?
Hi,
How can I invoke a method with parameters using reflections?
I want to the values to those parameters. Can somebody help?
In the java Reflection tutorial search for Invoking Methods by Name
You can use getClass in any Object to discover its class. Then you can use getMethods to discover all the available methods. Once you have the correct method you can call invoke with any number of parameters
this is the easiest way I know of, it needs to be surrounded with try & catch:
Method m = .class.getDeclaredMethod("", arg_1.class, arg_2.class, ... arg_n.class); result = () m.invoke(null,(Object) arg_1, (Object) arg_2 ... (Object) arg_n);
this is for invoking a static method, if you want to invoke a non static method, you need to replace the first argument of m.invoke() from null to the object the underlying method is invoked from.
don't forget to add an import to java.lang.reflect.*;
Here's a simple example of invoking a method using reflection involving primitives.
import java.lang.reflect.*;
public class ReflectionExample {
public int test(int i) {
return i + 1;
}
public static void main(String args[]) throws Exception {
Method testMethod = ReflectionExample.class.getMethod("test", int.class);
int result = (Integer) testMethod.invoke(new ReflectionExample(), 100);
System.out.println(result); // 101
}
}
To be robust, you should catch and handle all checked reflection-related exceptions NoSuchMethodException
, IllegalAccessException
, InvocationTargetException
.