类定义
package Reflect; public class MyTest {
public int a;
public static int b;
public static final int c = 0;
private int d; public int sum(int a, int b) {
return a + b;
} public int sub(int a, int b, String c) {
System.out.println(c);
return a - b;
} MyTest() { } MyTest(int a, int b) { }
}
反射调用
package Reflect; import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier; public class Test {
public static void main(String[] args) { // invoke the reflect-method
try {
final Class z = Class.forName("Reflect.MyTest");
final Class[] params = new Class[3];// define the param-type
params[0] = int.class;
params[1] = int.class;
params[2] = String.class; // final Method m = z.getDeclaredMethod("sub", params);
final Method m = z.getMethod("sub", int.class, int.class, String.class);
// final Method m = z.getDeclaredMethod("sum", int.class, int.class); // set in-param
final Object[] p = new Object[3];
p[0] = 100;
p[1] = 50;
p[2] = "hello word!"; System.out.println();
final Integer s = (Integer) m.invoke(z.newInstance(), p);
// final Integer s = (Integer) m.invoke(z.newInstance(), 3, 5);
System.out.println("return value==" + s);
} catch (final Exception e) {
e.printStackTrace();
} }
}
输出:
hello word!
return value==50