反射案例:借助注解动态调用指定类的指定方法

2 阅读1分钟

回顾:上一个反射案例,我们把类名、方法名写在外部配置文件中,程序读取文件后,利用反射动态创建对象、调用方法。

短板:外部配置文件路径容易出错、项目打包后加载麻烦、配置和代码分离。

思考:能不能把配置直接写在代码上?

方案:使用自定义注解来保存类名和方法名,程序通过反射读取注解信息,完成动态调用

学生类

package com.lwx.annotation;

public class Student {
    public void study() {
        System.out.println("学生正在学习 Java 注解");
    }
}

老师类

package com.lwx.annotation;

public class Teacher {
    public void teach() {
        System.out.println("老师正在讲授注解知识点");
    }
}

自定义注解

package com.lwx.annotation;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface MyAnnotation {
    String className();
    String methodName();
}

配置标记类(替代 config.properties)

package com.lwx.annotation;

// 切换注释,等价于切换properties
// @MyAnnotation(className = "com.lwx.annotation.Student", methodName = "study")
@MyAnnotation(className = "com.lwx.annotation.Teacher", methodName = "teach")
public class ConfigMarker {
}

执行器读取这个标记类上的注解,反射执行:

package com.lwx.annotation;

import java.lang.reflect.Method;

public class AnnotationConfigTest {
    public static void main(String[] args) throws Exception {
        // 获取ConfigMarker的字节码对象
        Class<ConfigMarker> cc = ConfigMarker.class;
        // 通过字节码文件对象获取注解对象
        MyAnnotation myAnnotation = cc.getAnnotation(MyAnnotation.class);

        // 从注解中获取全类名字符串
        String className = myAnnotation.className();
        // 从注解中获取要调用的方法名
        String methodName = myAnnotation.methodName();

        // 根据全类名,反射获取该类的Class字节码对象
        Class<?> clazz = Class.forName(className);
        // 通过无参构造器,反射创建该类的实例对象
        Object obj = clazz.getDeclaredConstructor().newInstance();
        // 根据方法名获取对应的方法对象
        Method method = clazz.getDeclaredMethod(methodName);
        // 在实例对象上,执行该方法
        method.invoke(obj);
    }
}