How can I invoke a method with parameters using reflection ?
I want to specify the values of those parameters.
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
.
To call a class method using reflection is very simple. You need to create a class and generate method in it. like as follows.
package reflectionpackage;
public class My {
public My() {
}
public void myReflectionMethod() {
System.out.println("My Reflection Method called");
}
}
and call this method in another class using reflection.
package reflectionpackage;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionClass {
public static void main(String[] args)
throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class c=Class.forName("reflectionpackage.My");
Method m=c.getDeclaredMethod("myReflectionMethod");
Object t = c.newInstance();
Object o= m.invoke(t);
}
}
Find more details here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With