三、提高反射效率 一、 如何提高反射的性能

反射机制对程序的运行在性能上有一定的影响,速度慢

1) 通过 setAccessible 提高性能

a) setAccessible 启用和禁用访问安全检查的开关,值为 true 则指示反射的对象在使用时应该取消 Java 语言访 问检查,值为 false 则指示反射的对象不实施 Java 语言 访问检查,并不是为 true 就能访问为 false 就不能访问

b) 禁止安全检查,可以提高反射的运行速度

 1 public class Test3 {
 2     public static void test01(){
 3         //User u=new User();
 4         Object obj=new Object();
 5         long startTime=System.currentTimeMillis();
 6         for(int i=0;i<1000000000L;i++){
 7             obj.hashCode();
 8         }
 9         long endTime=System.currentTimeMillis();
10         System.out.println("调用普通方法,执行10亿次:"+(endTime-startTime)+"ms");
11     }
12     public static void test02() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
13         Object obj=new Object();
14         Class c=obj.getClass();
15         //获取指定的方法
16         Method m=c.getDeclaredMethod("hashCode", null);
17         long startTime=System.currentTimeMillis();
18         for(int i=0;i<1000000000L;i++){
19             //执行这个方法
20             m.invoke(obj, null);
21         }
22         long endTime=System.currentTimeMillis();
23         System.out.println("通过反射动态方法调用,执行10亿次:"+(endTime-startTime)+"ms");
24     }
25     public static void test03() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
26         Object obj=new Object();
27         Class c=obj.getClass();
28         //获取指定的方法
29         Method m=c.getDeclaredMethod("hashCode", null);
30 
31         m.setAccessible(true);//不执行安全检查
32 
33         long startTime=System.currentTimeMillis();
34         for(int i=0;i<1000000000L;i++){
35             //执行这个方法
36             m.invoke(obj, null);
37         }
38         long endTime=System.currentTimeMillis();
39         System.out.println("通过反射动态方法调用,不启用安全检查,执行10亿次:"+(endTime-startTime)+"ms");
40     }
41     public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
42         test01();
43         test02();
44         test03();
45     }
46 }

三、提高反射效率
一、 如何提高反射的性能