反射——反射的优缺点和优化

反射的优缺点

  1. 优点:可以动态地创建和使用对象(也是框架底层核心),使用灵活,没有反射机制,框架技术就失去底层支撑。
  2. 缺点:使用反射基本是解释执行,对执行速度有影响

反射调用优化 - 关闭访问检查

  1. Method 和 Field、Constructor 对象都有 setAccessible() 方法
  2. setAccessible() 方法的作用是启动和禁用访问安全检查的开关
  3. 参数值为 true 表示反射的对象在使用时取消访问检查,提高反射的效率
  4. 参数值为 false 则表示反射的对象执行访问检查


package reflection_;

import java.lang.reflect.Method;

/**
 * @Author: Gin
 * @Description:
 * @Modified By: Gin
 * @Date: Created in 15:05 2021/9/28
 */
public class Reflection02 {
    public static void main(String[] args) throws Exception {
        m1();
        m2();
        m3();
    }

    // 传统方式调用方法
    public static void m1(){
        Cat cat = new Cat();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            cat.hello();
        }
        long end = System.currentTimeMillis();
        System.out.println("m1() 耗时 " + (end - start));
    }

    // 反射调用方法
    public static void m2() throws Exception{
        Class aClass = Class.forName("reflection_.Cat");
        Object o = aClass.newInstance();
        Method hello = aClass.getMethod("hello");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            hello.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println("m2() 耗时 " + (end - start));
    }

    // 反射调用方法优化
    public static void m3() throws Exception{
        Class aClass = Class.forName("reflection_.Cat");
        Object o = aClass.newInstance();
        Method hello = aClass.getMethod("hello");
        hello.setAccessible(true); // 在反射调用方法时,取消访问检查机制
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            hello.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println("m2() 耗时 " + (end - start));
    }

}



在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值