关于注解和反射的结合使用

123 阅读1分钟

创建一注解类

  • @Retention - 标识这个注解怎么保存,是只在代码中,还是编入class文件中,或者是在运行时可以通过反射访问。
    • @Retention(RetentionPolicy.RUNTIME) 的意思就是指定该 Annotation 的策略是 RetentionPolicy.RUNTIME。这就意味着,编译器会将该 Annotation 信息保留在 .class 文件中,并且能被虚拟机读取。
  • @Target - 标记这个注解应该是哪种 Java 成员。 更详细文档可以查看 菜鸟教程
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation {
    String value() default "auguigu";
}

查看文档可知 QQ截图20220602104034.png

@MyAnnotation(value = "hello")
public class MyAnnotationTest {
    public static void main(String[] args) {
        Class clazz = MyAnnotationTest.class;
        Annotation a = clazz.getAnnotation(MyAnnotation.class);
        MyAnnotation m = (MyAnnotation) a;
        String info = m.value();
        System.out.println(info);
    }
}

输出

hello

总结

更深刻地连接了反射可注解的使用,对java框架会有更好的理解方式