JavaSE 自定義註解

JavaSE 自定義註解

1.什麼是註解:

​ 註解就是一些特殊的接口

​ (百度百科)從JDK5開始,Java增加對元數據的支持,也就是註解,註解與註釋是有一定區別的,可以把註解理解爲代碼裏的特殊標記,這些標記可以在編譯,類加載,運行時被讀取,並執行相應的處理。通過註解開發人員可以在不改變原有代碼和邏輯的情況下在源代碼中嵌入補充信息。

2.常見的註解

​ @Override用來標記有幾成關係的類

​ @SupressWarining壓制警告

​ @Deprecated 過期生命

​ 還有兩種可以在自定義註解上註解;

​ @Target(ElementType) 代表自定義註釋可以註釋什麼 包括

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

​ @Rentention(RententionPolicy.*)自定義註解註解可以保留到什麼

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//在運行期間依舊存在
}

3.註解的定義方法

public @interface 註解名{
	Type  name()  default  n;//表示是什麼類型的註解參數,初始值是多少,當然也可以不寫
}

4.實際定義一個註解

@Target({ElementType.Type,ElementType.Metod})
@Retention(RetentionPolicy.RUNTiME)
public @interface Measurement{
    int group() default 10;
    int iterations(); default 1000;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章