To begin, we have a simple Java program in a "Program" class. In main, we indicate we can throw many exceptions.
import java.lang.reflect.*;
public class Program {
static void test() {
// Say hello.
System.out.println(
"Hello world");
}
static void bird(String message) {
// Print the argument.
System.out.print(
"Bird says: ");
System.out.println(message);
}
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
// Use getDeclaredMethod.
// ... This gets the test method by its name.
Method testMethod = Program.class.getDeclaredMethod(
"test");
// Invoke the test method.
testMethod.invoke(null, null);
// Use getDeclaredMethod.
// ... Get the bird method with a first argument of String.
Method birdMethod = Program.class.getDeclaredMethod(
"bird",
String.class);
// Invoke the bird method.
// ... First argument is class instance, which is null for a static method.
// Second argument is the actual argument String.
birdMethod.invoke(null,
"Seed");
}
}
Hello world
Bird says: Seed