[an error occurred while processing this directive]

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[0new Integer(30);
arg[1new Integer(40);
arg[2new Integer(50);
Object object = method.invoke(invoke, arg);
Integer integer = (Integer)object;
catch (Throwable e) {

Output will be displayed as:

Invoke Method Java

Download Source Code


[an error occurred while processing this directive]