How do I invoke a method using Method class?
Category: java.lang.reflect, viewed: 5030 time(s).
This example demonstrate using reflection to invoke methods of a class object. When using this method we need to catch for the NoSuchMethodException, IllegalAccessException and InvocationTargetException.
package org.kodejava.example.lang;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class InvokingMethod {
public static void main(String[] args) {
InvokingMethod object = new InvokingMethod();
Class clazz = object.getClass();
try {
//
// Invoking the add(int, int) method
//
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);
//
// Invoking the multiply(int, int) method
//
method = clazz.getMethod("multiply", new Class[] {int.class, int.class});
result = method.invoke(object, new Object[] {10, 10});
System.out.println("Result = " + result);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
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;
}
}
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!