1. 程式人生 > >java 元註解

java 元註解

工具 適用於 edi arrays string 舉例 地方 繼承 javascrip

1.概念講解

(轉載自:https://www.cnblogs.com/lyy-2016/p/6288535.html)

元註解是指註解的註解,包括@Retention @Target @Document @Inherited四種。

1.@Retention: 定義註解的保留策略
@Retention(RetentionPolicy.SOURCE) //註解僅存在於源碼中,在class字節碼文件中不包含
@Retention(RetentionPolicy.CLASS) // 默認的保留策略,註解會在class字節碼文件中存在,但運行時無法獲得,
@Retention(RetentionPolicy.RUNTIME) // 註解會在class字節碼文件中存在,在運行時可以通過反射獲取到
首 先要明確生命周期長度 SOURCE < CLASS < RUNTIME ,所以前者能作用的地方後者一定也能作用。一般如果需要在運行時去動態獲取註解信息,那只能用 RUNTIME 註解;如果要在編譯時進行一些預處理操作,比如生成一些輔助代碼(如 ButterKnife),就用 CLASS註解;如果只是做一些檢查性的操作,比如 @Override 和 @SuppressWarnings,則可選用 SOURCE 註解。


2.@Target:定義註解的作用目標
源碼為:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
@Target(ElementType.TYPE) //接口、類、枚舉、註解
@Target(ElementType.FIELD) //字段、枚舉的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法參數
@Target(ElementType.CONSTRUCTOR) //構造函數
@Target(ElementType.LOCAL_VARIABLE)//局部變量
@Target(ElementType.ANNOTATION_TYPE)//註解
@Target(ElementType.PACKAGE) ///包
3.@Document:說明該註解將被包含在javadoc中
4.@Inherited:說明子類可以繼承父類中的該註解

2.反射獲取註解

舉例:

技術分享圖片
// 適用類、接口(包括註解類型)或枚舉  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.TYPE)  
public @interface ClassInfo {  
    String value();  
}  
    
// 適用field屬性,也包括enum常量  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.FIELD)  
public @interface FieldInfo {  
    int[] value();  
}  
// 適用方法  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.METHOD)  
public @interface MethodInfo {  
    String name() default "long";  
    String data();  
    int age() default 27;  
}  
技術分享圖片

這3個註解分別適用於不同的元素,並都帶有不同的屬性,在使用註解是需要設置這些屬性值。
再定義一個測試類來使用這些註解:

技術分享圖片
@ClassInfo("Test Class")  
public class TestRuntimeAnnotation {  
 
    @FieldInfo(value = {1, 2})  
    public String fieldInfo = "FiledInfo";  
 
    @FieldInfo(value = {10086})  
    public int i = 100;  
 
    @MethodInfo(name = "BlueBird", data = "Big")  
    public static String getMethodInfo() {  
        return TestRuntimeAnnotation.class.getSimpleName();  
    }  
}  
在代碼中獲取註解信息:
private void _testRuntimeAnnotation() {  
    StringBuffer sb = new StringBuffer();  
    Class<?> cls = TestRuntimeAnnotation.class;  
    Constructor<?>[] constructors = cls.getConstructors();  
    // 獲取指定類型的註解  
    sb.append("Class註解:").append("\n");  
    ClassInfo classInfo = cls.getAnnotation(ClassInfo.class);  
    if (classInfo != null) {  
        sb.append(Modifier.toString(cls.getModifiers())).append(" ")  
                .append(cls.getSimpleName()).append("\n");  
        sb.append("註解值: ").append(classInfo.value()).append("\n\n");  
    }  
 
    sb.append("Field註解:").append("\n");  
    Field[] fields = cls.getDeclaredFields();  
    for (Field field : fields) {  
        FieldInfo fieldInfo = field.getAnnotation(FieldInfo.class);  
        if (fieldInfo != null) {  
            sb.append(Modifier.toString(field.getModifiers())).append(" ")  
                    .append(field.getType().getSimpleName()).append(" ")  
                    .append(field.getName()).append("\n");  
            sb.append("註解值: ").append(Arrays.toString(fieldInfo.value())).append("\n\n");  
        }  
    }  
 
    sb.append("Method註解:").append("\n");  
    Method[] methods = cls.getDeclaredMethods();  
    for (Method method : methods) {  
        MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);  
        if (methodInfo != null) {  
            sb.append(Modifier.toString(method.getModifiers())).append(" ")  
                    .append(method.getReturnType().getSimpleName()).append(" ")  
                    .append(method.getName()).append("\n");  
            sb.append("註解值: ").append("\n");  
            sb.append("name: ").append(methodInfo.name()).append("\n");  
            sb.append("data: ").append(methodInfo.data()).append("\n");  
            sb.append("age: ").append(methodInfo.age()).append("\n");  
        }  
    }  
 
    System.out.print(sb.toString());  
}  
技術分享圖片

3.Java源代碼如何處理註解

(轉載自:https://www.jianshu.com/p/e9329c8a59c2 作者:測試你個頭)

jdk中是通過AnnotatedElement(package java.lang.reflect)接口實現對註解的解析,我們的Class類實現了AnnotatedElement接口

public final class Class<T> implements java.io.Serializable,
                              GenericDeclaration,
                              Type,
                              AnnotatedElement {
  ......
}

AnnotatedElement代碼:

技術分享圖片

AnnotatedElement的註釋:
Represents an annotated element of the program currently running in this VM. This interface allows annotations to be read reflectively
翻譯過來就是:AnnotatedElement代表了jvm中一個正在運行的被註解元素,這個接口允許通過反射的方式讀取註解
可以看下Class類中對於AnnotatedElement接口都是如何實現的:

    /**
     * @throws NullPointerException {@inheritDoc}
     * @since 1.5
     */
    @SuppressWarnings("unchecked")
    public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
        Objects.requireNonNull(annotationClass);

        return (A) annotationData().annotations.get(annotationClass);
    }

    /**
     * {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     * @since 1.5
     */
    @Override
    public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
        return GenericDeclaration.super.isAnnotationPresent(annotationClass);
    }

    /**
     * @throws NullPointerException {@inheritDoc}
     * @since 1.8
     */
    @Override
    public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
        Objects.requireNonNull(annotationClass);

        AnnotationData annotationData = annotationData();
        return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
                                                          this,
                                                          annotationClass);
    }

    /**
     * @since 1.5
     */
    public Annotation[] getAnnotations() {
        return AnnotationParser.toArray(annotationData().annotations);
    }

    /**
     * @throws NullPointerException {@inheritDoc}
     * @since 1.8
     */
    @Override
    @SuppressWarnings("unchecked")
    public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
        Objects.requireNonNull(annotationClass);

        return (A) annotationData().declaredAnnotations.get(annotationClass);
    }

    /**
     * @throws NullPointerException {@inheritDoc}
     * @since 1.8
     */
    @Override
    public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
        Objects.requireNonNull(annotationClass);

        return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
                                                                 annotationClass);
    }

    /**
     * @since 1.5
     */
    public Annotation[] getDeclaredAnnotations()  {
        return AnnotationParser.toArray(annotationData().declaredAnnotations);
    }

上面的接口實現中,大致的原理都是一致的,我們挑選其中的getAnnotation方法來講解:

  • getAnnotation
    根據註解的class實例從類的註解緩存數據中獲取匹配的註解類型
    Controller是註解類型,Controller.getClass()獲取到的就是Class實例
    1、代碼中annotationData().annotations是一個Map(key為註解的Class實例,value為註解類型),源碼為:
    // annotation data that might get invalidated when JVM TI RedefineClasses() is called
    private static class AnnotationData {
        final Map<Class<? extends Annotation>, Annotation> annotations;
        final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;

        // Value of classRedefinedCount when we created this AnnotationData instance
        final int redefinedCount;

        AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
                       Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
                       int redefinedCount) {
            this.annotations = annotations;
            this.declaredAnnotations = declaredAnnotations;
            this.redefinedCount = redefinedCount;
        }
    }

2、annotationData()的源碼是:

    private AnnotationData annotationData() {
        while (true) { // retry loop
            AnnotationData annotationData = this.annotationData;
            int classRedefinedCount = this.classRedefinedCount;
            if (annotationData != null &&
                annotationData.redefinedCount == classRedefinedCount) {
                return annotationData;
            }
            // null or stale annotationData -> optimistically create new instance
            AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
            // try to install it
            if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
                // successfully installed new AnnotationData
                return newAnnotationData;
            }
        }
    }

核心的邏輯是:當this.annotationData為空,解析類中的annotationData並寫入this.annotationData,最後都會返回this.annotationData

3、其中Atomic.casAnnotationData(this, annotationData, newAnnotationData)的作用便是將解析到的annotationData寫入this.annotationData

        static <T> boolean casAnnotationData(Class<?> clazz,
                                             AnnotationData oldData,
                                             AnnotationData newData) {
            return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData);
        }

其中unsafe.compareAndSwapObject是一個native方法
4、而createAnnotationData(classRedefinedCount)的作用是解析類中用到的annotationData

    private AnnotationData createAnnotationData(int classRedefinedCount) {
        Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
            AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
        Class<?> superClass = getSuperclass();
        Map<Class<? extends Annotation>, Annotation> annotations = null;
        if (superClass != null) {
            Map<Class<? extends Annotation>, Annotation> superAnnotations =
                superClass.annotationData().annotations;
            for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
                Class<? extends Annotation> annotationClass = e.getKey();
                if (AnnotationType.getInstance(annotationClass).isInherited()) {
                    if (annotations == null) { // lazy construction
                        annotations = new LinkedHashMap<>((Math.max(
                                declaredAnnotations.size(),
                                Math.min(12, declaredAnnotations.size() + superAnnotations.size())
                            ) * 4 + 2) / 3
                        );
                    }
                    annotations.put(annotationClass, e.getValue());
                }
            }
        }
        if (annotations == null) {
            // no inherited annotations -> share the Map with declaredAnnotations
            annotations = declaredAnnotations;
        } else {
            // at least one inherited annotation -> declared may override inherited
            annotations.putAll(declaredAnnotations);
        }
        return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
    }

整個的處理邏輯是:
1、獲取類本身的declaredAnnotations
2、獲取父類的annotations
3、將declaredAnnotations+annotations整合,返回

Annotation解析的範例代碼:

@Component
public class SSHClient {
  ......
}
public class AnnotationHelper {

    public static void main(String[] args) {
        Annotation[] annotations = new Annotation[0];

        annotations = SSHClient.class.getAnnotations();

        for (Annotation annotation : annotations) {
            System.out.println(annotation.toString());
            System.out.println(annotation.annotationType());
            System.out.println(annotation.getClass().getName());
            System.out.println(annotation.getClass().getTypeName());
            System.out.println(annotation.getClass().toString());
        }

        if (SSHClient.class.isAnnotationPresent(Component.class)) {
            System.out.println("find Component annotation");
        }

        Annotation annotation = SSHClient.class.getAnnotation(Component.class);

        System.out.println(annotation.toString());
        System.out.println(annotation.annotationType());
        System.out.println(annotation.getClass().getName());
        System.out.println(annotation.getClass().getTypeName());
        System.out.println(annotation.getClass().toString());
    }
}

執行結果:


技術分享圖片

可以看到,通過Annotation接口中定義的annotationType()可以獲取Annotation的類型

實際應用中,比如spring框架中對註解的解析有專門的工具類,但是都是基於AnnotatedElement中定義的方法來實現的

以上,就是整個元註解和註解解析相關的講解。

java 元註解