Java Method.invoke(Object obj, Object ... args)
Syntax
Method.invoke(Object obj, Object ... args) has the following syntax.
public Object invoke(Object obj, Object ... args)
throws IllegalAccessException ,
IllegalArgumentException ,
InvocationTargetException
Example
In the following code shows how to use Method.invoke(Object obj, Object ... args) method.
import java.lang.reflect.Method;
//www . jav a2 s.c om
class X {
public void objectMethod(String arg) {
System.out.println("Instance method: " + arg);
}
public static void classMethod() {
System.out.println("Class method");
}
}
public class Main {
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("X");
X x = (X) clazz.newInstance();
Class[] argTypes = { String.class };
Method method = clazz.getMethod("objectMethod", argTypes);
Object[] data = { "Hello" };
method.invoke(x, data); // Output: Instance method: Hello
method = clazz.getMethod("classMethod", (Class<?>[]) null);
method.invoke(null, (Object[]) null); // Output: Class method
} catch (Exception e) {
System.err.println(e);
}
}
}
The code above generates the following result.