This section provides a tutorial example on how to reflect class methods as Method instances and invoke them directly.
Once a class is loaded as a Class instance, you can reflect its methods as Method instances
and invoke them directly like this:
ClassLoader l = ClassLoader.getSystemClassLoader();
Class c = l.loadClass(className);
Object o = c.newInstance();
Method m = c.getMethod(methodName, parameterTypes);
m.invoke(o, args);
Here is tutorial example program showing you how to invoke a method reflected as a Method instance:
/**
* ClassMethodReflection.java
* Copyright (c) 2010 by Dr. Herong Yang, herongyang.com
*/
import java.lang.reflect.*;
class ClassMethodReflection {
static java.io.PrintStream out = System.out;
public static void main(String[] a) {
try {
// Loading the class and creating an object
ClassLoader l = ClassLoader.getSystemClassLoader();
Class c = l.loadClass("java.util.Random");
Object o = c.newInstance();
// Reflecting a specific method: nextInt(int n)
Method m = c.getMethod("nextInt", int.class);
// Invoking the method: o.nextInt(100)
Object r = m.invoke(o, 100);
out.println("Random number between 0 and 99: "+r);
} catch (Exception e) {
e.printStackTrace();
}
}
}
When executed on my Windows XP system with JDK 1.6.0,
I got this result:
C:\herong\jvm>javac ClassMethodReflection.java
Note: ClassMethodReflection.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
C:\herong\jvm>java ClassMethodReflection
Random number between 0 and 99: 66
C:\herong\jvm>java ClassMethodReflection
Random number between 0 and 99: 23
C:\herong\jvmjava ClassMethodReflection
Random number between 0 and 99: 47