示例:
package annoAndRe.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test08 {
//普通方法调用1亿次
public static void test01() {
People people = new People();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
people.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方法调用10亿次需要: " + (endTime - startTime) + "ms");
}
// 反射方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
People people = new People();
Class c1 = people.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
getName.invoke(people, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方式调用10亿次需要: " + (endTime - startTime) + "ms");
}
// 反射方式调用 关闭监测
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
People people = new People();
Class c1 = people.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
long startTime = System.currentTimeMillis();
getName.setAccessible(true);
for (int i = 0; i < 100000000; i++) {
getName.invoke(people, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方式调用 关闭监测10亿次需要:" + (endTime - startTime) + " ms ");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
}
class People {
private String name;
public People() {
}
public People(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
运行结果: