Share on Google+Share on Google+

Invoke Method in Java

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;
catch (Throwable e) {

Output will be displayed as:

Invoke Method Java

Download Source Code



Posted on: November 15, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Invoke Method in Java   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
October 13, 2011
wrong number of arguments

java.lang.IllegalArgumentException: wrong number of arguments the object "arg[]" contains 3 elements and the method add only accept 2 arguments.
August 28, 2012
code given in download and web page is different

hi , I found that there is a error in the coding given in the web page. things to be corrected. public int add(int a, int b) { return a + b; } change to public int add(int a, int b, int c) { return a + b + c; } Class partypes[] = new Class[2]; change the above to this Class partypes[] = new Class[3]; Add: partypes[2] = Integer.TYPE;
Ask You
August 30, 2012
It's Wrong Code

//Please see the following: 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[2]; 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); } } }