0
点赞
收藏
分享

微信扫一扫

Java反射之注解加反射

unadlib 2022-01-06 阅读 217
  1. 自定义注解
import java.lang.annotation.*;

@Target({ElementType.FIELD,ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface pro {
    String className() ;
    String methodName() ;
}
  1. 核心代码(使用注解的方式实现配置类加载)
import annotation.pro;
import java.lang.reflect.Method;

@pro(className = "Entity.Student", methodName = "sleep")
public class ReflectCase2 {
    public static void main(String[] args) throws Exception {
        // 1.获取字节码文件
        Class<ReflectCase2> reflectCaseClass = ReflectCase2.class;
        // 2.获取注解
        pro annotation = reflectCaseClass.getAnnotation(pro.class);
        //3.加载注解
        String className = annotation.className();
        String methodName = annotation.methodName();
        // 4.创建对象和方法
        Class aClass = Class.forName(className);
        Object obj = aClass.newInstance();
        Method method = aClass.getMethod(methodName);
        method.invoke(obj);
    }
}
举报

相关推荐

0 条评论