Java使用反射处理注解

来源:互联网 发布:施工进度网络计划软件 编辑:程序博客网 时间:2024/06/05 01:59

Annotation: 注解,代码里的特殊标记,JDK1.5开始引入,这些标记可以在编译、类加载、运行时被读取,并执行相应的处理。通过注解,开发人员可以在不改变原有逻辑的情况下,在源文件中嵌入一些补充的信息。APT(Annotation Processor Tool)可以通过这些补充信息进行验证、处理或者进行部署,通过反射机制在进行必要的处理。

自定义注解

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface DoItLikeThis {    /**     * @return - The description.     */    String description() default "";    /**     * @return - The action.     */    String action() default "";    /**     * @return - Should we be doing it like this.     */    boolean shouldDoItLikeThis() default false;}

@Target:定义了注解修饰的对象范围

  • ElementType.CONSTRUCTOR :用于描述构造器
  • ElementType.FIELD :用于描述域
  • ElementType.LOCAL_VARIABLE :用于描述局部变量
  • ElementType.METHOD :用于描述方法
  • ElementType.PACKAGE :用于描述包
  • ElementType.PARAMETER :用于描述参数
  • ElementType.TYPE :用于描述类、接口(包括注解类型) 或enum声明

@RetentionPolicy:定义注解保留时间长短

  • SOURCE:在原文件中有效,被编译器丢弃。
  • CLASS:在class文件有效,但会被虚拟机忽略。
  • RUNTIME:在运行时有效。
@Slf4jpublic class AnnotatedClassProcessor {    public void processClass(AnnotatedClass ac) {        log.info("start");        Annotation[] annotations = ac.getClass().getAnnotations();        for (Annotation annotation : annotations) {            log.info("class name is {}, annotation type is {}", ac.getClass().getName(), annotation.annotationType());        }        if (ac.getClass().isAnnotationPresent(DoItLikeThis.class)) {            DoItLikeThis doItLikeThis = ac.getClass().getAnnotation(DoItLikeThis.class);            log.info("annotation in class is {}", doItLikeThis);            Field[] fields = ac.getClass().getDeclaredFields();            for (Field field : fields) {                if (field.isAnnotationPresent(DoItLikeThat.class)) {                    DoItLikeThat doItLikeThat = field.getAnnotation(DoItLikeThat.class);                    log.info("field name is {}, field annotation is {}", field.getName(), doItLikeThat);                }            }            Method[] methods = ac.getClass().getMethods();            for (Method method : methods) {                if (method.isAnnotationPresent(DoItWithWhiffleBallBat.class)) {                    DoItWithWhiffleBallBat doItWithWhiffleBallBat = method.getAnnotation(DoItWithWhiffleBallBat.class);                    log.info("method name is {}, method annotation is {} ", method.getName(), doItWithWhiffleBallBat);                }            }        }        log.info("end");    }}

反射中涉及的三种类型Class, Field, and Method 都实现了AnnotatedElement接口,包含以下方法:

  • getAnnotations():返回该元素上的所有注解,包括从父类继承的。
  • getDeclaredAnnotations() :只返回该元素上所包含的注解
  • getAnnotation(Class《A》 annotationClass) :返回指定类型元素的注解,如果该元素上没有指定类型的注解,则返回NULL
  • isAnnotation() :该元素上是否包含注解
  • isAnnotationPresent(Class《? Extends Annotation> annotationClass) :该元素上是否包含指定注解
原创粉丝点击