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
原文地址:https://www.cnblogs.com/li33/p/12741061.html