Java注解Annotation使用

2022-06-25 10:27:26 浏览数 (1)

Java注解Annotation的使用

RuntimeAnnotation注解

代码语言:javascript复制
package annotation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface RuntimeAnnotation {
}

ClassAnnotation注解

代码语言:javascript复制
package annotation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface ClassAnnotation {
}

枚举类AnType中使用注解

代码语言:javascript复制
package annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public enum AnType {

    @RuntimeAnnotation
    @ClassAnnotation
    TYPE_TEST_1,


    @ClassAnnotation
    TYPE_TEST_2;


    /**
     * 注解使用:可以在运行时通过反射判断某字段是否有某注解进而进行一些操作
     */
    public boolean isRuntimeAnnotation(){

        Field field = new Field();

        try {
            /**
             * 通过反射获取该对象在枚举中的字段
             */
            field = this.getClass().getField(this.name());
        } catch (Exception e) {

        }

        return isFieldAnnotated(field, RuntimeAnnotation.class);

    }

    /**
     * 该field的注解中是否匹配输入的注解
     */
    private boolean isFieldAnnotated(Field field, Class<? extends Annotation> annotationClass) {
        if (field == null) {
            return false;
        }

        /**
         * annotations中有RuntimeAnnotation,但是没有ClassAnnotation
         * 因为RuntimeAnnotation被注解为Runtime,可以被反射出来
         */
        Annotation[] annotations = field.getAnnotations();
        if(annotations == null || annotations.length == 0){
            return false;
        }
        for (Annotation annotation : annotations) {
            if (annotation.annotationType().equals(annotationClass)) {
                return true;
            }
        }
        return false;
    }

}

0 人点赞