How to Invoke Methods by Name using JAVA reflection

Discussion in 'Java' started by imran, Feb 1, 2005.

  1. imran

    imran Guest


    I have a code that invoke methods by name. But in this code it just
    invoke int a and int b. How can i modify to invoke another data,
    String and Double. Actually i want to design fault injection tools.
    Below is the code and can someone help me to solve the above problem.
    I welcome with example source code.
    Thank you....

    import java.lang.reflect.*;

    public class method2 {

    public int add(int a, int b) //////// the problem here
    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;
    catch (Throwable e) {
    imran, Feb 1, 2005
    1. Advertisements

  2. Hi Imran!
    By modifying the parameter types and the arguments as needed.
    If you want to invoke a method declared as
    int gggg(Double d, String s)
    then you modify your code below like this:
    partypes[0] = Double.class;
    partypes[1] = String.class;
    arglist[0] = new Double(37.123);
    arglist[1] = "efgebeasqaff";
    Thomas Fritsch, Feb 1, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.