[ Back | Previous | Next ]

How to use invoke() of Method with parameters?

Package:
java.lang.reflect.*
Product:
JDK
Release:
1.0.2
Related Links:
General
Field
Method
Comment:
import java.lang.reflect.*;

public class Invoke {

    public static void main (String[] args) {
        new Invoke ();
    }

    public Invoke () {
        int i = 56;
        
        Object result = new Object ();

        try {
            Class c = this.getClass ();
            Object[] args_value = { new Integer (i) };

            Class[] args_class = { Class.forName ("java.lang.Integer") };

            try {
                // this fails!
                Method m = c.getMethod ("test", args_class);
                
                try {
                    result = m.invoke (this, args_value);
                } catch (Exception e) {
                    System.err.println ("Failed to invoke: " + e.toString ());
                }

            } catch (Exception e) {
                System.err.println ("Failed to get method: " + e.toString ());
            }

        } catch (Exception e) {
            System.err.println ("Error: " + e.toString ());         
        }
        
        System.out.println ("Result=" + result);
    }

    // getMethod fails to find this method (I want this)
    public String test (int i) {
        return "int=" + new Integer (i).toString ();
    }

    // This is what getMethod() wants to find (but I don't won't it)
    /*
    public String test (Integer i) {
        return "Integer=" + i.toString ();
    }
    */
}