In Java, java.lang.reflect.*; package is required to import in the program to invoke the methods.
Invoke Method in Java
In Java, java.lang.reflect.*; package is required to import in the
program to invoke the
methods. As you can see here we are using reflect method, this could be
either a class method or instance method and the usage of methods in Java is to access a single method either on class or interface.
This example will show you, how to declare and invoke the methods in Java.
Code for Java Method - Invoke
import java.lang.reflect.*;
public class InvokeMethod {
public int add(int a, int b)
{
return a + b;
}
public static void main(String args[]){
try {
Class cla = Class.forName("InvokeMethod");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method method = cla.getMethod(
"add", partypes);
InvokeMethod invoke = new InvokeMethod();
Object arg[] = new Object[3];
arg[0] = new Integer(30);
arg[1] = new Integer(40);
arg[2] = new Integer(50);
Object object = method.invoke(invoke, arg);
Integer integer = (Integer)object;
System.out.println(integer.intValue());
}
catch (Throwable e) {
System.out.println(e);
}
}
} |
Output will be displayed as:
Download Source Code