Java注解Annotation使用

Java注解Annotation的使用

RuntimeAnnotation注解

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注解

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中使用注解

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;
    }

}

猜你喜欢

转载自blog.csdn.net/shinecjj/article/details/82901550