setAccessible(true)對方法性能的影響


setAccessible

分析性能,直接使用方法最快,然后關閉檢測會稍慢,包含檢測的是最慢的。

setAccessible(true)是關閉方法的公有或者私有檢測,拿來直接用這個方法。

在獲取到getName方法之后調用!


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test07 {
    public static void test01(){
        User user = new User ();
        long startTime = System.currentTimeMillis ();
        for (int i = 0; i < 1000000000; i++) {
            user.getName ();
        }
        long endTime = System.currentTimeMillis ();
        System.out.println ("普通方法執行10億次"+(endTime-startTime)+"ms");
    }
    public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User ();
        Class c1 = user.getClass ();
        Method getName = c1.getMethod ("getName");//getName方法被得到
        long startTime = System.currentTimeMillis ();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke (user,null);//傳入gameName方法來使用getName()
        }
        long endTime = System.currentTimeMillis ();
        System.out.println ("反射執行10億次"+(endTime-startTime)+"ms");
    }
    public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User ();
        Class c1 = user.getClass ();
        Method getName = c1.getMethod ("getName");//Method類專門接受方法
        getName.setAccessible (true);//表示不檢測方法是否為public或者private
        long startTime = System.currentTimeMillis ();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke (user,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();
    }
}
結果:
普通方法執行10億次535ms
反射執行10億次45781ms
關閉檢測執行10億次7396ms


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM