Home Java Java-methods Invoke Method in Java



Invoke Method in Java
Posted on: November 15, 2008 at 12:00 AM
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[0new Integer(30);
arg[1new Integer(40);
arg[2new 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:

Invoke Method Java

Download Source Code

Related Tags for Invoke Method in Java:
javacclassuiinterfaceimportmethodsmethodportusinginstanceintthispackageinvokeusageprogramtoramrequiresinglerefldlaneitcanulimceinasstamntsagecajpackaceclesagemeproackseeesspackisirandarccrtsausavassthavstaccessfaceeitherprndodsonogro


More Tutorials from this section

Ask Questions?    Discuss: Invoke Method in Java   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.