java中的Annotation在定義的時候,通常會寫以下代碼java
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface Slf4j {
/**
* Sets the category of the constructed Logger. By default, it will use the type where the annotation is placed.
*/
String topic() default "";
}
複製代碼
其中會用到以下幾個註解 android
主要有以下:程序員
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
複製代碼
ElementType內容以下:bash
取值 | 描述 |
---|---|
ANNOTATION_TYPE | 應用於註解類型 |
CONSTRUCTOR | 用於構造函數 |
FIELD | 用於字段或屬性 |
LOCAL_VARIABLE | 局部變量上使用 |
METHOD | 方法上註釋 |
PACKAGE | 用於包的聲明上 |
PARAMETER | 做用於方法參數上 |
TYPE | 用於類的任何元素 |
==由於@Target是使用在Annotation上的,因此他的@Target(ElementType.ANNOTATION_TYPE)==app
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
複製代碼
RetentionPolicy取值以下:函數
取值 | 描述 |
---|---|
SOURCE | 只做用於編譯階段,而且會被編譯器丟棄 |
CLASS | 在編譯後會被放進class文件,可是在虛擬機運行期無效(==默認值==) |
RUNTIME | 編譯後會被放進class文件,在運行期間有效 |
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface Slf4j {
/**
* Sets the category of the constructed Logger. By default, it will use the type where the annotation is placed.
*/
String topic() default "";
}
複製代碼
lombok.extern.slf4j下的@slf4j註解,是在編譯器自動生成代碼。因此在運行期間是沒有做用的,因此能夠寫成RetentionPolicy.SOURCE,生成class文件能夠將其丟棄。ui
對於服務端程序員來講,代碼編譯成class文件,後面就是去運行,處於運行期了,因此註解若是隻是在class文件中,會被虛擬機忽略的話,和沒進class有什麼區別呢??
網上查的資料以下: 首先咱們知道android從源碼到apk文件的大致流程: Java源碼 —> Class文件 —> Dex文件 —> apk
因此在安卓程序的開發過程當中,寫進Class文件的註解能夠在class文件->app過程當中起做用spa
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
複製代碼
默認狀況下,生成javedoc文件的時候,Annotation是不包含在javadoc中的,加上@Documented以後,這個annotation能夠出如今javadoc中code
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
複製代碼
Inherited的中文意思就是 遺傳的
因此@Inherited的做用是,若是父類中標註了由@Inherited修飾的註解時,子類能夠從父類中==遺傳==這個註解cdn
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable {
/**
* Indicates the <em>containing annotation type</em> for the
* repeatable annotation type.
* @return the containing annotation type
*/
Class<? extends Annotation> value();
}
複製代碼
上述的幾個註解都是在1.5的時候就有了,@Repeatable比較年輕,是在1.8的時候才引入的,做用是能夠在一個位置可使用屢次@Repeatable修飾的註解 實例:
@Repeatable(value = Repeats.class)
public @interface Repeat {
String value();
}
public class RepeatDemo {
@Repeat(value = "tag")
@Repeat(value = "tag2")
public void method() {
}
}
複製代碼