How to Invoke Methods by Name using JAVA reflection

From: m.imran (m.imran.1js56n_at_mail.codecomments.com)
Date: 02/01/05


Date: Tue, 1 Feb 2005 06:53:42 -0600


hi,

I have write a code to invoke methods by name. Below is the sourcecode
that i have writen. The problem is, how can i pass data String or
Double to method "add". This source code just invoke int a and int b.
Actually from this source code i want to design Fault Injection Tools
and i still beginner in JAVA. I hope someone can help me and i also
welcome who given example of sourcecode.

Thank you...
import java.lang.reflect.*;

public class method2 {

        public int add(int a, int b)
        {
                return a + b;
        }
        
        public static void main(String args[])
        {
            try {
                             Class cls = Class.forName("method2");
                             Class partypes[] = new Class[2];

                          partypes[0] = Integer.TYPE;
                          partypes[1] = Integer.TYPE;

                          Method meth = cls.getMethod( "add", partypes);
                          method2 methobj = new method2();
                          Object arglist[] = new Object[2];

                          arglist[0] = new Integer(37);
                          arglist[1] = new Integer(47);

                          Object retobj = meth.invoke(methobj, arglist);
                          Integer retval = (Integer)retobj;
                          System.out.println(retval.intValue());
                  }
                  catch (Throwable e) {
                        System.err.println(e);
                   }
                }
        }

--
m.imran
------------------------------------------------------------------------
Posted via http://www.codecomments.com
------------------------------------------------------------------------
 

Loading