Java反射學習總結五(Annotation(註解)-基礎篇)

來源:互聯網
上載者:User

標籤:ati   任務   學習總結   適用於   定義   相同   調用   eth   present   

Annotation(註解)簡單介紹:

註解大家印象最深刻的可能就是JUnit做單元測試,和各種架構裡的使用了。

本文主要簡介一下註解的用法,下篇文章再深入的研究。

annotation並不直接影響代碼語義。可是它可以被看作類似程式的工具或者類庫。它會反過來對正在執行的程式語義有所影響。

annotation能夠從源檔案,class檔案或者以在執行時反射的多種方式被讀取


java註解系統內建有主要下面幾個註解:

Override註解表示子類要重寫(override)父類的相應方法

Deprecated註解表示方法是不建議被使用的

Suppress Warnings註解表示抑制警告


怎樣自己定義註解:

僅僅須要使用@interface來定義一個註解,比如:

//使用@interface來聲明一個註解(實際上是自己主動繼承了java.lang.annotation.Annotation介面)public @interface AnnotationTest {String value1() default "hello";  //為註解設定String類型的屬性Value1,並使用defalutkeyword設定預設值EnumTest value2();//設定枚舉類型的value2String[] value3();//設定數群組類型的value3}
怎樣來使用註解呢,例如以下:

@AnnotationTest(value2 = EnumTest.age, value3={""})public class AnnotationUsage {@AnnotationTest(value1 = "Test", value2 = EnumTest.name, value3={""})String test;@AnnotationTest(value1 = "Test", value2 = EnumTest.name, value3={""})public void method(){System.out.println("usage of Annotation");}}
如上,註解能夠標註在屬性。方法。類上。

須要使用name=value這樣的賦值方式為屬性賦值,由於value1設定了預設屬性,所以能夠忽略,假設沒有設定預設值則全部的屬性都要一一賦值。



另一種特殊情況,假設註解裡僅僅定義了一個屬性,名字是value,那麼能夠直接賦值,不須要使用name=value這樣的賦值方式。例如以下:

public @interface AnnotationTest {String value();}@AnnotationTest("test")public void method(){System.out.println("usage of Annotation");}

修飾註解的“註解”

註解也能夠加入註解的“註解”去修飾,經常使用的有下面兩個,一個是Retention。一個Target

Retention:

使用Retention必需要提供一個為java.lang.annotation.RetentionPolicy類型的的枚舉

RetentionPolicy枚舉有下面3個類型:

SOURCE:編譯器時處理完Annotation資訊後就完畢任務

CLASS:編譯器將Annotation儲存於class檔案裡,不能夠由虛擬機器讀入

RUNTIME:編譯器將Annotation儲存於class檔案裡。能夠由虛擬機器讀入

用這三種Retention的Prolicy能夠決定註解是從源檔案。class檔案或者以在執行時反射被讀取

關於Retention的範例在最後


Target:

使用java.lang.annotation.Target能夠定義註解被使用的位置

相同,在使用時要指定一個java.lang.annotation.ElementType的枚舉實值型別為他的“屬性”

ElementType枚舉的類型例如以下:

ANNOTATION_TYPE:適用於annotation
CONSTRUCTOR:適用於構造方法
FIELD:適用於field
LOCAL_VARIABLE:適用於局部變數
METHOD:適用於方法
PACKAGE:適用於package
PARAMETER:適用於method上的parameter
TYPE:適用於class,interface,enum

例如以下:定義一個註解MyTarget。設定Target類型為Method來修飾這個註解。這樣這個註解僅僅能標註在method的方法上

@Target(ElementType.METHOD)public @interface MyTarget { String hello() default "hello";}

@MyTarget  //這裡則會報錯,由於他標註在類上面了public class MyTargetTest {@MyTarget   //標註在方法上不會報錯public void doSomething(){System.out.println("hello world");}}


使用反射調用註解
在下面的類中Class Constructor Field Method Package等類都實現了AnnotatedElement介面在介面中有下面重要的方法:
getAnnotations(Class annotationType)擷取一個指定的annotation類型
getAnnotations() 擷取全部的Annotation
getDeclaredAnnotations() 擷取聲明過的全部Annotation
isAnnotationPresent(Class<? extends Annotation> annotationClass)這個annotation是否出現
通過這些方法,配合反射我們就能夠在程式執行時拿到註解的內容了。範例例如以下:
@Retention(RetentionPolicy.RUNTIME)//定義一個註解。使用Retention標註為RUNTIMEpublic @interface MyAnnotation {String hello() default "hello";String world();}

該註解被標示為runtime類型,表示該註解最後能夠儲存在class檔案裡,並為java虛擬機器在執行時讀取到

@Retention(RetentionPolicy.CLASS)//定義一個註解。Retention標註為RUNTIMEpublic @interface MyAnnotation2 {String hello() default "hello"; //設定預設值為hello}
自己定義的還有一個註解Retention標示為class

public class MyTest {@SuppressWarnings("unchecked")  //java內建的註解Retention的policy為SOURCE@Deprecated//java內建的註解Retention的policy為RUNTIME@MyAnnotation(Name="Dean", Age="25")//自己定義的註解Retention的policy為RUNTIME@MyAnnotation2//自己定義的註解Retention的policy為CLASSpublic void TestMethod() {System.out.println("this is a method");}}
定義一個TestMethod方法。給他標示了4個註解。當中2個java內建的,2個我們自己定義的。註解的的Retention屬性各不同樣。

以下定義一個測試類來驗證結果:

public static void main(String[] args) throws Exception {MyTest myTest = new MyTest();//通過反射得到TestMethod方法Class<MyTest> c = MyTest.class;Method method = c.getMethod("TestMethod", new Class[]{});//AnnotatedElement介面中的方法isAnnotationPresent(),推斷傳入的註解類型是否存在if (method.isAnnotationPresent(MyAnnotation.class)) {method.invoke(myTest, new Object[]{});//AnnotatedElement介面中的方法getAnnotation(),擷取傳入註解類型的註解MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);//拿到註解中的屬性String name = myAnnotation.Name();String age = myAnnotation.Age();System.out.println("name:"+name +"   age:"+age);}System.out.println("-----------------------------------");//AnnotatedElement介面中的方法getAnnotations(),擷取全部註解Annotation[] annotations = method.getAnnotations();//迴圈註解數組列印出註解類型的名字for (Annotation annotation : annotations) {System.out.println(annotation.annotationType().getName());}}
列印結果為:

this is a method
name:Dean   age:25
-----------------------------------
java.lang.Deprecated
gxy.text.annotation.MyAnnotation


切割線上:介紹了怎樣使用AnnotatedElement介面中的方法和反射去調用註解

切割線下:證明了僅僅有定義了Retention的Policy為Runtime的註解才幹夠被反射讀取出來


下一篇文章分析一下在JUnit中反射與註解的使用和原理

Java反射學習總結五(Annotation(註解)-基礎篇)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.