反射 Reflect

反射的定义

反射用于在程序 运行时 ,获取并调用未知类的字段、方法等信息

反射的功能

  1. 判断是否为某个类的实例
    使用Class 对象的 isInstance() 方法来判断是否为某个类的实例,它是一个 native 方法
    在这里插入图片描述
  2. 使用反射创建对象
  3. 调用方法、成员变量。用例见文末。

反射的运用场景

  1. Spring中,XML 配置模式装载 Bean
  2. 日志打印时,使用的反射获取类信息
  3. 向视图层返回数据时,对数据按注解再次处理,用例

调用方法、成员变量 用例:

需求:现有一批方法的执行链,所有方法都代表一个项目,需要根据不同项目调用不同的方法(现已存储项目于方法名的对应),且方法执行中有一个对象来保存执行过程里需要的数据。

 public static void main(String[] args) {
        AvailableDetectionServiceImpl service = new AvailableDetectionServiceImpl();//AvailableDetectionServiceImpl 为业务类
        Class<? extends AvailableDetectionServiceImpl> aClass = service.getClass();
        DetectionBuilder detectionBuilder = new DetectionBuilder();//为保存方法执行链中需要的数据对象
        try {
            Method test = aClass.getDeclaredMethod("test", DetectionBuilder.class);
             test.invoke(service, detectionBuilder);
            System.out.println(detectionBuilder.getDetection().getBussinessId());// in my test

            Method test1 = aClass.getDeclaredMethod("test1", DetectionBuilder.class);
            test1.invoke(service, detectionBuilder);
            System.out.println(detectionBuilder.getDetection().getBussinessId());// in my test  in my test1 
 
        } catch (Exception a) {
            a.printStackTrace();
        }
    }

    public DetectionBuilder test(DetectionBuilder db) {
        Detection detection = new Detection();
        detection.setBussinessId(" in my test ");
        db.setDetection(detection);
        return db;
    }

    public DetectionBuilder test1(DetectionBuilder db) {
        String doccode = db.getDetection().getBussinessId();
        db.getDetection().setBussinessId(doccode + " in my test1 ");
        return db;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值