自定义Java注解(一)
概念
注解是Java語言5.0版本開始支持加入源代碼的特殊語法元數(shù)據(jù)(描述數(shù)據(jù)的數(shù)據(jù))有點像Class(描述類的類)
要自定義注解,必須先了解Java提供的幾個基本的元注解及其相關(guān)的語法
Java的幾個元注解
- @Target
- @Retention
- @Inherited
- @Documented
@Target
SourceCode:
package java.lang.annotation; /*** Defines a meta-annotation for determining what {@link ElementType}s an* annotation can be applied to.** @since 1.5*/ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target {ElementType[] value(); }@Target能夠指定注解作用的范圍,注解、構(gòu)造器、域、局部變量、方法、包、參數(shù)、類、接口、枚舉它有以下8個值
| ANNOTATION_TYPE | 作用于注解類型 |
| CONSTRUCTOR | 作用于構(gòu)造器 |
| FIELD | 作用于域 |
| LOCAL_VARIABLE | 作用于局部變量 |
| METHOD | 作用于方法 |
| PACKAGE | 作用于包 |
| PARAMETER | 作用于參數(shù) |
| TYPE | 作用于描述類、接口、枚舉 |
如果自定義的注解沒有指定@Target,默認該注解可以使用在上述所有范圍,如果存在@Target則編譯器會強制實施相應(yīng)的使用規(guī)則,例如如果@Target指定是ANNOTATION_TYPE
則MyAnnotation只能用在注解上,不能用在其他范圍
@MyAnnotation //right public @interface AnotherAnnotation{... }@MyAnnotation //compile error public class MyClass{.... }如果要作用于多個范圍,使用大括號中間用逗號隔開,注意括號內(nèi)不能存在相同的ElementType值否則編譯錯誤。eg如下
@Target({ElementType.TYPE,ElementType.METHOD}) public @interface MyAnnotation {...}@Retention
SourceCode:
package java.lang.annotation;/*** Defines a meta-annotation for determining the scope of retention for an* annotation. If the retention annotation is not set {@code* RetentionPolicy.CLASS} is used as default retention.** @since 1.5*/ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Retention {RetentionPolicy value(); }@Retention指定注解的生命周期即保留的時間,如果未聲明@Retention默認使用的保留策略為RetentionPolicy.CLASS
| CLASS | 存在源文件、編譯的Class字節(jié)碼中,運行時VM不在保留 |
| RUNTIME | 存在源文件、編譯的Class字節(jié)碼中,運行時VM會保存,且能通過反射獲取注解 |
| SOURCE | 保留在源文件中,編譯器會丟棄 |
@Inherited
SourceCode:
package java.lang.annotation; /*** Defines a meta-annotation for indicating that an annotation is automatically* inherited.* @since 1.5*/ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Inherited { }分析源碼可知@Inherited只能修飾注解,它表示該注解類型被自動繼承,如果用戶在當(dāng)前類中查詢這個元注解類型并且當(dāng)前類的聲明中不包含這個元注解類型,那么也將自動查詢當(dāng)前類的父類是否存在Inherited元注解,這個動作將被重復(fù)執(zhí)行直到這個標(biāo)注類型被找到,或者是查詢到頂層的父類
@Documented
SourceCode:
package java.lang.annotation; /*** Defines a meta-annotation for indicating that an annotation is documented and* considered part of the public API.* @since 1.5*/ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Documented { }@Documented:表示擁有該注解的元素可通過javadoc此類的工具進行文檔化。該類型應(yīng)用于注解那些影響客戶使用帶注(comment)的元素聲明的類型。如果類型聲明是用Documented來注解的,這種類型的注解被作為被標(biāo)注的程序成員的公共API
一個簡單應(yīng)用注解的示例
總結(jié)
以上是生活随笔為你收集整理的自定义Java注解(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android如何优雅地防止Bean类混
- 下一篇: Android 任意区域截屏