日期:2014-05-16  浏览次数:21065 次

提高java反射速度的方法method.setAccessible(true)
提高java反射速度的方法method.setAccessible(true) 2011.12.19阅读(3)下一篇:开机后,桌面上没... |返回日志列表 赞赞赞赞转载分享评论复制地址编辑

1.import  java.lang.reflect.InvocationTargetException;     
2.import  java.lang.reflect.Method;     
3.    
4.public   class  Main {     
5.    public   static   void  main(String[] args)  throws  SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {     
6.        Method m = A.class .getDeclaredMethod( "getName" ,  new  Class[]{});     
7.        System.out.println(m.isAccessible());     
8.                //getName是public的,猜猜输出是true还是false      
9.             
10.        A a = new  A();     
11.        a.setName("Mr Lee" );     
12.        long  start = System.currentTimeMillis();     
13.        for ( int  i= 0 ;i< 10000000 ;i++){     
14.            m.invoke(a, new  Object[]{});     
15.        }     
16.        System.out.println( "Simple              :"  +(System.currentTimeMillis() - start));     
17.             
18.        m.setAccessible(true ); //注意此处不同      
19.        long  start1 = System.currentTimeMillis();     
20.        for ( int  i= 0 ;i< 10000000 ;i++){     
21.            m.invoke(a, new  Object[]{});     
22.        }     
23.        System.out.println("setAccessible(true) :" +( System.currentTimeMillis() - start1));     
24.    }     
25.}     
26.class  A{     
27.    private  String name;     
28.    public  String getName() {     
29.        return  name;     
30.    }     
31.    public   void  setName(String name) {     
32.        this .name = name;     
33.    }     
34.}   
测试结果



引用



false

Simple              :4969

setAccess