09.Java 基礎 - 註解
基本概念
Annotion (註解)是一個接口,程式可以透過反射來取得指定程式元素的Annotion 對象,然後透過Annotion 物件來取得註解裡面的元資料。
根據註解的使用方法和用途,我們可以將 Annotation 分為三類:系統註解,元註解,自訂註解。
系統註解
系統註解,也就是 JDK 內建的註解,主要有:@Override,@Deprecated,@SuppressWarnnings。
1.@Override
修飾方法時表示方法覆寫了父類別的方法,或實作介面的方法
interface Demo{ public void print(); }public class Test implements Demo{ @Override public void print() { } }
2.@Deprecated
修飾已經過時的方法
3.@SuppressWarnnings
抑制編譯器警告,即移除警告。
常見的參數值有:
名稱 | #作用 |
---|---|
rawtypes | |
#deprecation | |
unchecked | |
fallthrough | |
path | |
#serial | |
finally | |
all |
實例如下:// 抑制单类型@SuppressWarnings("unchecked")public void print() { @SuppressWarnings("rawtypes")
List list = new ArrayList();
list.add("a");
}// 抑制多类型@SuppressWarnings({ "unchecked", "rawtypes" })public void print() {
List list = new ArrayList();
list.add("a");
}// 抑制所有类型@SuppressWarnings({ "all" })public void print() {
List list = new ArrayList();
list.add("a");
}
登入後複製
// 抑制单类型@SuppressWarnings("unchecked")public void print() { @SuppressWarnings("rawtypes") List list = new ArrayList(); list.add("a"); }// 抑制多类型@SuppressWarnings({ "unchecked", "rawtypes" })public void print() { List list = new ArrayList(); list.add("a"); }// 抑制所有类型@SuppressWarnings({ "all" })public void print() { List list = new ArrayList(); list.add("a"); }
#元註解
元註解的功能就是負責註解其他註解。 Java5.0 定義了4 個標準的meta-annotation
類型,它們被用來提供對其它 annotation 類型作說明。定義的元註解如下:@Target,@Retention,@Documented,@Inherited。
1.@Target
@Target 定義了Annotation所修飾的物件範圍,具體的修飾範圍如下:public enum ElementType { // 用于描述类、接口(包括注解类型) 或enum声明
TYPE, // 用于描述域(即变量)
FIELD, // 用于描述方法
METHOD, // 用于描述参数
PARAMETER, // 用于描述构造器
CONSTRUCTOR, // 用于描述局部变量
LOCAL_VARIABLE, // 用于描述注解类型
ANNOTATION_TYPE, // 用于描述包
PACKAGE
}
登入後複製
public enum ElementType { // 用于描述类、接口(包括注解类型) 或enum声明 TYPE, // 用于描述域(即变量) FIELD, // 用于描述方法 METHOD, // 用于描述参数 PARAMETER, // 用于描述构造器 CONSTRUCTOR, // 用于描述局部变量 LOCAL_VARIABLE, // 用于描述注解类型 ANNOTATION_TYPE, // 用于描述包 PACKAGE }
2.@Retention
@Retention 定義了該Annotation 被保留的時間長短,即指明了Annotation 的生命週期。 public enum RetentionPolicy { // 在源文件中有效(编译器要丢弃的注解)
SOURCE, // class 文件中有效(默认,编译器将把注解记录在类文件中,但在运行时 VM 不需要保留注解)
CLASS, // 在运行时有效(编译器将把注解记录在类文件中,在运行时 VM 将保留注解,因此可以反射性地读取)
RUNTIME
}
登入後複製
public enum RetentionPolicy { // 在源文件中有效(编译器要丢弃的注解) SOURCE, // class 文件中有效(默认,编译器将把注解记录在类文件中,但在运行时 VM 不需要保留注解) CLASS, // 在运行时有效(编译器将把注解记录在类文件中,在运行时 VM 将保留注解,因此可以反射性地读取) RUNTIME }
3.@Documented
#@Documented 定義 Annotation ,表示某一類型的註解將透過 javadoc 和類似的預設工具進行文件化。如果類型宣告是用 Documented 來註解的,則其註解將成為註解元素的公共 API 的一部分。
4.@Inherited
- @Inherited 定義Annotation ,表示註解類型被自動繼承,即一個使用了@Inherited 修飾的annotation 類型被用於一個class,則這個annotation 將會被用於該class的子類別。
- 使用註解類型註解 class 以外的任何事物,@Inherited 都是無效的。
- 此元註解僅促成從父類別繼承註解;對已實作介面的註解無效。
實例如下:// 定义注解@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Inherited@interface MyAnotation{
public String name();
}// 作用在类上@MyAnotation(name="parent")
class Parent{
}// 继承 Parent 类public class Test extends Parent{
public static void main(String[] args) {
Class<?> cls = Test.class; // 通过 @Inherited 继承父类的注解
Annotation annotation = cls.getAnnotation(MyAnotation.class);
MyAnotation myAnotation = (MyAnotation) annotation;
System.out.println(myAnotation.name());
}
}// 输出结果:parent(若注释掉注解,返回异常)
登入後複製
// 定义注解@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Inherited@interface MyAnotation{ public String name(); }// 作用在类上@MyAnotation(name="parent") class Parent{ }// 继承 Parent 类public class Test extends Parent{ public static void main(String[] args) { Class<?> cls = Test.class; // 通过 @Inherited 继承父类的注解 Annotation annotation = cls.getAnnotation(MyAnotation.class); MyAnotation myAnotation = (MyAnotation) annotation; System.out.println(myAnotation.name()); } }// 输出结果:parent(若注释掉注解,返回异常)
自訂註解
1.類別註解
// 定义注解@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@interface MyAnnotation {
public String name(); public String age();
}// 调用注解@MyAnnotation(name="cook",age="100")public class Test {
public static void main(String[] args) {
Class<?> cls = Test.class; // 1.取得所有注解
Annotation[] annotations =cls.getAnnotations(); // 2.取得指定注解
MyAnnotation annotation =
(MyAnnotation)cls.getAnnotation(MyAnnotation.class);
}
}
登入後複製
// 定义注解@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@interface MyAnnotation { public String name(); public String age(); }// 调用注解@MyAnnotation(name="cook",age="100")public class Test { public static void main(String[] args) { Class<?> cls = Test.class; // 1.取得所有注解 Annotation[] annotations =cls.getAnnotations(); // 2.取得指定注解 MyAnnotation annotation = (MyAnnotation)cls.getAnnotation(MyAnnotation.class); } }
2.方法註解
// 定义注解@Retention(RetentionPolicy.RUNTIME)
// 修改作用范围@Target(ElementType.METHOD)@interface MyAnnotation { public String name(); public String age();
}
// 调用注解public class Test {
public static void main(String[] args) throws Exception {
Class cls = Test.class;
Method method = cls.getDeclaredMethod("print", null); // 1.取得所有注解
Annotation[] annotations = method.getDeclaredAnnotations(); // 2.取得指定注解
MyAnnotation annotation =
(MyAnnotation)method.getAnnotation(MyAnnotation.class);
}
登入後複製
// 定义注解@Retention(RetentionPolicy.RUNTIME) // 修改作用范围@Target(ElementType.METHOD)@interface MyAnnotation { public String name(); public String age(); } // 调用注解public class Test { public static void main(String[] args) throws Exception { Class cls = Test.class; Method method = cls.getDeclaredMethod("print", null); // 1.取得所有注解 Annotation[] annotations = method.getDeclaredAnnotations(); // 2.取得指定注解 MyAnnotation annotation = (MyAnnotation)method.getAnnotation(MyAnnotation.class); }
3.參數註解
// 定义注解@Retention(RetentionPolicy.RUNTIME)
// 修改作用范围@Target(ElementType.PARAMETER)@interface MyAnnotation { public String name(); public String age();
}public class Test {
public static void main(String[] args) throws Exception {
Class cls = Test.class;
Method method = cls.getDeclaredMethod("print", new Class[]{String.class,String.class});
getAllAnnotations(method);
} // 作用在参数上
public void print(@MyAnnotation(name = "cook", age = "100")
String name, String age) { } public static void getAllAnnotations(Method method) {
Annotation[][] parameterAnnotions = method.getParameterAnnotations();
// 通过反射只能取得所有参数类型,不能取得指定参数
Class[] paraemterTypes = method.getParameterTypes();
int i = 0;
for (Annotation[] annotations : parameterAnnotions) {
Class paraemterType = paraemterTypes[i++];
for (Annotation annotation : annotations) {
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println(paraemterType.getName());
System.out.println(myAnnotation.name());
System.out.println(myAnnotation.age());
}
}
}
}
}
登入後複製
// 定义注解@Retention(RetentionPolicy.RUNTIME) // 修改作用范围@Target(ElementType.PARAMETER)@interface MyAnnotation { public String name(); public String age(); }public class Test { public static void main(String[] args) throws Exception { Class cls = Test.class; Method method = cls.getDeclaredMethod("print", new Class[]{String.class,String.class}); getAllAnnotations(method); } // 作用在参数上 public void print(@MyAnnotation(name = "cook", age = "100") String name, String age) { } public static void getAllAnnotations(Method method) { Annotation[][] parameterAnnotions = method.getParameterAnnotations(); // 通过反射只能取得所有参数类型,不能取得指定参数 Class[] paraemterTypes = method.getParameterTypes(); int i = 0; for (Annotation[] annotations : parameterAnnotions) { Class paraemterType = paraemterTypes[i++]; for (Annotation annotation : annotations) { if (annotation instanceof MyAnnotation) { MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println(paraemterType.getName()); System.out.println(myAnnotation.name()); System.out.println(myAnnotation.age()); } } } } }
#4.變數註解
// 定义注解@Retention(RetentionPolicy.RUNTIME) // 修改作用范围@Target(ElementType.FIELD)@interface MyAnnotation { public String name(); public String age(); }public class Test { // 作用在变量上 @MyAnnotation(name = "cook", age = "100") private String name; public static void main(String[] args) throws Exception { Class cls = Test.class; Field field = cls.getDeclaredField("name"); Annotation[] fieldAnnotions = field.getDeclaredAnnotations(); MyAnnotation annotation = (MyAnnotation) field.getAnnotation(MyAnnotation.class); } }
以上就是09.Java 基礎- 註解的內容,更多相關內容請關注PHP中文網(www.php.cn)! ##########

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

Java 8引入了Stream API,提供了一種強大且表達力豐富的處理數據集合的方式。然而,使用Stream時,一個常見問題是:如何從forEach操作中中斷或返回? 傳統循環允許提前中斷或返回,但Stream的forEach方法並不直接支持這種方式。本文將解釋原因,並探討在Stream處理系統中實現提前終止的替代方法。 延伸閱讀: Java Stream API改進 理解Stream forEach forEach方法是一個終端操作,它對Stream中的每個元素執行一個操作。它的設計意圖是處

Java是熱門程式語言,適合初學者和經驗豐富的開發者學習。本教學從基礎概念出發,逐步深入解說進階主題。安裝Java開發工具包後,可透過建立簡單的「Hello,World!」程式來實踐程式設計。理解程式碼後,使用命令提示字元編譯並執行程序,控制台上將輸出「Hello,World!」。學習Java開啟了程式設計之旅,隨著掌握程度加深,可創建更複雜的應用程式。
