执行结果如下:
result = -23853056
In Calc1, Time used is 307 MilliSeconds
result = -47706112
In Calc2 (Reflection), Time used is 6347 MilliSeconds
源代码如下
(1)目标测试类 TRef.java:
public class TRef {
int delta = 3245320;
static int result = 0;
public void Result() {
TRef.result += delta;
}
}
(2)主程序类:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class tReflection {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
tReflection t = new tReflection();
t.Calc1();
t.Calc2();
}
void Calc1() {
TRef r = new TRef();
long i =0, j = 100000000;
Date t1 = new Date();
for (;i < j; i++) {
r.Result();
}
Date t2 = new Date();
System.out.println("result = " + TRef.result);
System.out.println("In Calc1, Time used is " + (t2.getTime() - t1.getTime()) + " MilliSeconds");
}
void Calc2() {
TRef r = new TRef();
long i =0, j = 100000000;
Method m = null;
try {
m = TRef.class.getMethod("Result");//, (Class<?>[])null);
} catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Date t1 = new Date();
for (;i < j; i++) {
m.invoke(r, (Object[]) null);
}
Date t2 = new Date();
System.out.println("result = " + TRef.result);
System.out.println("In Calc2, Time used is " + (t2.getTime() - t1.getTime()) + " MilliSeconds");
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}