Calling a Method
Home ] Up ] Reconstructing a Class ] Inspecting a Class Instance ] Instantiating an Object ] Creating an Array ] [ Calling a Method ] An Example ]

 

 

Just as the Constructor class provides a newInstance() method to invoke a chosen constructor for a class, so the Method class provides an invoke() method to call a chosen method in the class:

public native Object invoke(Object obj,
                            Object[] args) 
    throws IllegalAccessException, 
           IllegalArgumentException, 
           InvocationTargetException

Here's a snippet of an example:

        Class c = emp.getClass(); // (or similar)
           ...
        // Find a suitable method
        Class[] methodParams = new Class[]
        {
            String.class, int.class, 
            double.class, long.class
        };
        Method method;
        try
        {
            method = c.getMethod("init", methodParams);
        }
        catch(NoSuchMethodException e)
        {
            System.err.println("Can't find method");
            return;
        }
        
        // Construct parameter list for call
        Object[] paramValues = new Object[]
        {
            "Launcelot Hobgoblin", new Integer(57),
            new Double(560000.00), new Long(34567)
        };
        // Do the call...
        try
        {
            method.invoke(emp, paramValues);
        }
        catch(IllegalAccessException e)
        {
            System.err.println("Unable to access class");
        }
        catch(InvocationTargetException e)
        {
            System.err.println("Invocation target threw exception");
        }
 
The page was last updated February 19, 2008