性能对比分析
public static void main(String[] args) throws Exception {
test01();
test02();
test03();
}
//普通反射调用
public static void test01(){
Person person = new Person();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
person.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方法执行需要的时间"+(endTime-startTime)+"ms");
}
//通过反射反射调用
public static void test02() throws Exception {
Person person = new Person();
Class c1 = Class.forName("com.saxon.reflection.Person");
Method getName = c1.getMethod("getName", null);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
getName.invoke(person,null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方法执行需要的时间"+(endTime-startTime)+"ms");
}
//反射方式调用 关闭检测
public static void test03() throws Exception {
Person person = new Person();
Class c1 = Class.forName("com.saxon.reflection.Person");
Method getName = c1.getMethod("getName", null);
getName.setAccessible(true);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
getName.invoke(person,null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射关闭检测方法执行需要的时间"+(endTime-startTime)+"ms");
}
//执行结果:
普通方法执行需要的时间1ms
反射方法执行需要的时间221ms
反射关闭检测方法执行需要的时间52ms