註解與註釋的區別:
- 簡單來說,註釋是給人看的不會被編譯器執行,註解是用來修飾代碼的,會被編譯器執行。
*四大元註解:
-
@Retention: 定義註解的生命週期,註解將會在什麼時候從源碼中消失。
-
RetentionPolicy.SOURCE:註解僅存在於源碼中,編譯時就會消失
-
RetentionPolicy.CLASS: 默認的保留策略,註解會在class字節碼文件中存在,但運行時會消失。
-
RetentionPolicy.RUNTIME: 註解會在class字節碼文件中存在,在運行時可以通過反射獲取到
-
-
@ Target:定義註解的修飾目標,就是說當前註解可以用來修飾哪些對象。
-
TYPE :接口、類、枚舉、註解
-
FIELD:字段、枚舉的常量
-
METHOD :方法
-
PARAMETER:方法參數
-
CONSTRUCTOR:構造函數
-
LOCAL_VARIABLE:局部變量
-
ANNOTATION_TYPE:註解
-
PACKAGE:包
-
-
@Document:說明該註解將被包含在javadoc中
-
@Inherited:說明子類可以繼承父類中的該註解
實現自定義註解:
1、首先實現一個註解類
註解有一個name屬性,target註解指明當前註解只能修飾屬性
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD })
public @interface MyAnnotation {
public String name();
}
2、使用這個註解
import java.lang.reflect.Field;
public class AnnoTest {
@MyAnnotation(name = "wang")
static String name;
int i;
/**
* 利用反射技術,拿到註解的內容
*/
public static void main(String[] args) throws ClassNotFoundException {
// 根據全路徑名拿到類實例
Class cls = Class.forName("MyAnnotation.AnnoTest");
// 拿到所有實例的屬性
Field[] fs = cls.getDeclaredFields();
// 遍歷所有屬性
for (Field f : fs) {
// 如果當前屬性含有MyAnnotation註解
if (f.isAnnotationPresent(MyAnnotation.class)) {
// 拿到註解對象
MyAnnotation a = f.getAnnotation(MyAnnotation.class);
// 拿到註解的屬性
name = a.name();
}
}
System.out.println(name);
}
}
總結:先自定義註解類,在類中聲明需要的屬性。然後在需要的地方使用註解。然後利用反射技術拿到註解的內容。