元注解(注解的注解)
a. @Retention
它是被定義在一個注解類的前面,用來說明該注解的生命周期。
它有以下參數:
RetentionPolicy.SOURCE:指定注解只保留在源文件當中。
RetentionPolicy.CLASS:指定注解只保留在class文件中。(缺省)
RetentionPolicy.RUNTIME:指定注解可以保留在程序運行期間。
b. @Target
它是被定義在一個注解類的前面,用來說明該注解可以被聲明在哪些元素前。(默認可以放在任何元素之前)
它有以下參數:
ElementType.TYPE:說明該注解只能被聲明在一個類、接口、枚舉前。
ElementType.FIELD:說明該注解只能被聲明在一個類的字段前。
ElementType.METHOD:說明該注解只能被聲明在一個類的方法前。
ElementType.PARAMETER:說明該注解只能被聲明在一個方法參數前。
ElementType.CONSTRUCTOR:說明該注解只能聲明在一個類的構造方法前。
ElementType.LOCAL_VARIABLE:說明該注解只能聲明在一個局部變量前。
ElementType.ANNOTATION_TYPE:說明該注解只能聲明在一個注解類型前。
ElementType.PACKAGE:說明該注解只能聲明在一個包名前。
c. @Inherited 表明該注解將會被子類繼承。
需要說明的是,加上該元注解的注解,只有用在類元素上才有效果。這是在JDK總的原話:
Note that this meta-annotation type has no effect if the annotated
type is used to annotate anything other than a class. Note also
that this meta-annotation only causes annotations to be inherited
from superclasses; annotations on implemented interfaces have no
effect
但是在其他元素上的注解,只要你沒有覆蓋父類中的元素,是會繼承過來的。這就是為什么有getDeclaredAnnotations()和getAnnotations()的原因。
d. @Documented
表明在生成JavaDoc文檔時,該注解也會出現在javaDoc文檔中。