|
Invoke methods
The following example shows how to invoke static and instance methods using java reflection API.
|
package com.bethecoder.tutorials.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class InvokeMethod {
/**
* @param args
*/
public static void main(String[] args) {
Calculator cal = new Calculator("Simple Math");
//Invoke 'add' method on 'cal' instance
try {
Method method = cal.getClass().getMethod("add", int.class, int.class);
Integer sum = (Integer) method.invoke(cal, 4, 8);
System.out.println("sum : " + sum);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//Invoke static 'toString' method
try {
Method method = Calculator.class.getMethod("toString", Calculator.class);
//Pass 'null' as this is static method and we require no instance
String str = (String) method.invoke(null, cal);
System.out.println("str : " + str);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
class Calculator {
private String name;
public Calculator(String name) {
this.name = name;
}
public int add(int i, int j) {
return i + j;
}
public static String toString(Calculator cal) {
return "Calculator[" + cal.name + "]";
}
}
|
| |
It gives the following output,
sum : 12
str : Calculator[Simple Math]
|
|