反射的定义
反射用于在程序 运行时 ,获取并调用未知类的字段、方法等信息
反射的功能
- 判断是否为某个类的实例
使用Class 对象的 isInstance() 方法来判断是否为某个类的实例,它是一个 native 方法
- 使用反射创建对象
- 调用方法、成员变量。用例见文末。
反射的运用场景
- Spring中,XML 配置模式装载 Bean
- 日志打印时,使用的反射获取类信息
- 向视图层返回数据时,对数据按注解再次处理,用例
调用方法、成员变量 用例:
需求:现有一批方法的执行链,所有方法都代表一个项目,需要根据不同项目调用不同的方法(现已存储项目于方法名的对应),且方法执行中有一个对象来保存执行过程里需要的数据。
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;
}