|
|
|
|
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:
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 |