Invoke a method using Method class
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
MyClass object = new MyClass();
Class clazz = object.getClass();
Method method = clazz.getMethod("add", new Class[] { int.class, int.class });
Object result = method.invoke(object, new Object[] { 10, 10 });
System.out.println("Result = " + result);
method = clazz.getMethod("multiply", new Class[] { int.class, int.class });
result = method.invoke(object, new Object[] { 10, 10 });
System.out.println("Result = " + result);
}
}
class MyClass{
public int add(int numberA, int numberB) {
return numberA + numberB;
}
public int multiply(int numberA, int numberB) {
return numberA * numberB;
}
public double div(int numberA, int numberB) {
return numberA / numberB;
}
}
Related examples in the same category