1. 程式人生 > >Java註解Annotation使用

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

}