java.lang.annotation包類的淺析

一、先看一下annotation包下的類,做者的jdk是1.6版本。java


Annotation是接口,the common interface extended by all annotation types,意思就就是說Annotation是全部註解類型的父類型,我的感受就像是註解’界‘的Object,Annotation有四個方法,可是自定義的註解是不能夠重寫Annotation這四個方法的。這與Object中的不一樣之處。jvm

二、@interface Retention函數

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    RetentionPolicy value();
}

Retention:「保留,拘留」的意思。在註解中用於標識註解被保留多久(因爲註解的保留的屬性不一樣,在jvm中駐留的時間也不一樣)若是在註解上沒加@Retention註解,則默認的保留策略是ClASS。該註解做用範圍就是在註解上,用於屬性和方法是不起做用的。spa

三、RetentionPolicy.net

接上面的策略說:code

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,
    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,
    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

SOURCE:註解將在編譯的時候被忽略;繼承

ClASS:編譯以後註解將被保留在字節碼文件中,可是在不會在vm運行時保留。默認策略;接口

RUNTIME:註解會保留在字節碼文件中,同時在vm運行時始終存在,並且能夠經過反射獲取相對應的信息。get

四、@interface Targetit

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    ElementType[] value();
}


Target是指示該註解適用的範圍,若是Target元註解沒有在註解上聲明,該自定義的註解能夠在程序的任何地方使用。若是在Target中出現超過一次的一樣的ElementType的枚舉值,就會報編譯時錯誤。若是在Target({})這樣使用,該註解就不能在外部使用了。

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,
    /** Field declaration (includes enum constants) */
    FIELD,
    /** Method declaration */
    METHOD,
    /** Parameter declaration */
    PARAMETER,
    /** Constructor declaration */
    CONSTRUCTOR,
    /** Local variable declaration */
    LOCAL_VARIABLE,
    /** Annotation type declaration */
    ANNOTATION_TYPE,
    /** Package declaration */
    PACKAGE
}


使用範圍:

TYPE:類、接口、註解、枚舉類型;
FIELD:屬性;
METHOD:方法;
PARAMETER:參數;
CONSTRUCTOR:構造函數;
LOCAL_VARIABLE:局部變量
ANNOTATION_TYPE:註解類型;
PACKAGE:包;

五、@Inherited

使用該Meta-annotation意思是該註解能夠被自動繼承。若是自定義註解聲明瞭@Inherited,子類就會沿着繼承樹去查找有改表示的註解。除了在類上使用外,用在其餘地方的都不起做用。只能在繼承的狀況下起做用,若是實現一個藉口@Inherited也是不起做用的。


六、@Documentd

Indicates that annotations with a type are to be documented by javadoc and similar tools by default。

暫時寫這些,待更新,若有錯誤請望輕拍^_^!

相關文章
相關標籤/搜索