Re: How to Invoke Methods by Name using JAVA reflection

From: Lars-Inge Tønnessen [VJ# MVP] (http://emailme.larsinge.com)
Date: 02/01/05


Date: Tue, 1 Feb 2005 19:21:17 +0100


This is how I would have done it:

In this code we don't know "anything" about "method2()". We are using

   Class cls = Class.forName( "method2" );
   Object o = cls.newInstance();

to create a new object, and

   Method meth = cls.getMethod( "add", partypes );
   Object retobj = meth.invoke( o, arglist );

to get the result from the method.

With don't have to know anything specific like this:

     method2 methobj = new method2();

import java.lang.reflect.*;

public class method2
{

 public int add(int a, int b, String _str, Double _dob )
 {
  System.out.println( _str + " : " + _dob );
  return a + b;
 }

 public static void main(String args[])
 {
  try
  {
   Class partypes[] = new Class[4];

   partypes[0] = Integer.TYPE;
   partypes[1] = Integer.TYPE;
   partypes[2] = String.class;
   partypes[3] = Double.class;

   Object arglist[] = new Object[4];
   arglist[0] = new Integer(37);
   arglist[1] = new Integer(47);
   arglist[2] = new String("hello");
   arglist[3] = new Double(3.4);

   Class cls = Class.forName( "method2" );
   Object o = cls.newInstance();
   Method meth = cls.getMethod( "add", partypes );
   Object retobj = meth.invoke( o, arglist );
   Integer retval = (Integer)retobj;
   System.out.println( retval );
  }
  catch (Exception e)
  {
   e.printStackTrace();
   System.err.println(e);
  }
 }
}

Regards,
Lars-Inge Tønnessen


Loading