Java注釋@interface的用法【轉】

來源:互聯網
上載者:User

標籤:rgs   type   方法   nbsp   exception   efault   img   output   工具   

    Java用  @interface Annotation{ } 定義一個註解 @Annotation,一個註解是一個類。
@Override,@Deprecated,@SuppressWarnings為常見的3個註解。
註解相當於一種標記,在程式中加上了註解就等於為程式加上了某種標記,以後,
JAVAC編譯器,開發工具和其他程式可以用反射來瞭解你的類以及各種元素上有無任何標記,看你有什麼標記,就去幹相應的事。

      註解@Override用在方法上,當我們想重寫一個方法時,在方法上加@Override,當我們方法
的名字出錯時,編譯器就會報錯,


       註解@Deprecated,用來表示某個類的屬性或方法已經過時,不想別人再用時,在屬性和方法
上用@Deprecated修飾,

 

  註解@SuppressWarnings用來壓製程序中出來的警告,比如在沒有用泛型或是方法已經過時的時候,
 

  

註解@Retention可以用來修飾註解,是註解的註解,稱為元註解。
Retention註解有一個屬性value,是RetentionPolicy類型的,Enum RetentionPolicy是一個枚舉類型,
這個枚舉決定了Retention註解應該如何去保持,也可理解為Rentention 搭配 RententionPolicy使用。RetentionPolicy有3個值:CLASS  RUNTIME   SOURCE
用@Retention(RetentionPolicy.CLASS)修飾的註解,表示註解的資訊被保留在class檔案(位元組碼檔案)中當程式編譯時間,但不會被虛擬機器讀取在啟動並執行時候;
用@Retention(RetentionPolicy.SOURCE )修飾的註解,表示註解的資訊會被編譯器拋棄,不會留在class檔案中,註解的資訊只會留在源檔案中;
用@Retention(RetentionPolicy.RUNTIME )修飾的註解,表示註解的資訊被保留在class檔案(位元組碼檔案)中當程式編譯時間,會被虛擬機器保留在運行時,
所以他們可以用反射的方式讀取。RetentionPolicy.RUNTIME 可以讓你從JVM中讀取Annotation註解的資訊,以便在剖析器的時候使用.

 

[java] view plain copy 
    1. package com.self;  
    2. import java.lang.annotation.Retention;  
    3. import java.lang.annotation.RetentionPolicy;  
    4.   
    5. @Retention(RetentionPolicy.RUNTIME)  
    6. public @interface MyTarget  
    7. { }  
    8. 定義個一註解@MyTarget,用RetentionPolicy.RUNTIME修飾;  
    9. package com.self;  
    10. import java.lang.reflect.Method;  
    11. public class MyTargetTest  
    12. {  
    13.  @MyTarget  
    14.  public void doSomething()  
    15.  {  
    16.   System.out.println("hello world");  
    17.  }  
    18.    
    19.  public static void main(String[] args) throws Exception  
    20.  {  
    21.   Method method = MyTargetTest.class.getMethod("doSomething",null);  
    22.   if(method.isAnnotationPresent(MyTarget.class))//如果doSomething方法上存在註解@MyTarget,則為true  
    23.   {  
    24.    System.out.println(method.getAnnotation(MyTarget.class));  
    25.   }  
    26.   }  
    27. }  
    28. 上面程式列印:@com.self.MyTarget(),如果RetentionPolicy值不為RUNTIME,則不列印。  
    29.   
    30.  @Retention(RetentionPolicy.SOURCE )  
    31. public @interface Override  
    32.   
    33. @Retention(RetentionPolicy.SOURCE )  
    34. public @interface SuppressWarnings  
    35.   
    36. @Retention(RetentionPolicy.RUNTIME )  
    37. public @interface Deprecated  
    38. 由上可以看出,只有註解@Deprecated在運行時可以被JVM讀取到  
    39.   
    40. 註解中可以定義屬性,看例子:  
    41. @Retention(RetentionPolicy.RUNTIME)  
    42. public @interface MyAnnotation  
    43. {  
    44.  String hello() default "gege";  
    45.   String world();  
    46.   int[] array() default { 2, 4, 5, 6 };  
    47.   EnumTest.TrafficLamp lamp() ;  
    48.   TestAnnotation lannotation() default @TestAnnotation(value = "ddd");  
    49.   Class style() default String.class;  
    50. }  
    51. 上面程式中,定義一個註解@MyAnnotation,定義了6個屬性,他們的名字為:  
    52. hello,world,array,lamp,lannotation,style.  
    53. 屬性hello類型為String,預設值為gege  
    54. 屬性world類型為String,沒有預設值  
    55. 屬性array類型為數組,預設值為2,4,5,6  
    56. 屬性lamp類型為一個枚舉,沒有預設值  
    57. 屬性lannotation類型為註解,預設值為@TestAnnotation,註解裡的屬性是註解  
    58. 屬性style類型為Class,預設值為String類型的Class類型  
    59.   
    60. 看下面例子:定義了一個MyTest類,用註解@MyAnnotation修飾,註解@MyAnnotation定義的屬性都賦了值  
    61. @MyAnnotation(hello = "beijing", world="shanghai",array={},lamp=TrafficLamp.RED,style=int.class)  
    62. public class MyTest  
    63. {  
    64.  @MyAnnotation(lannotation=@TestAnnotation(value="baby"), world = "shanghai",array={1,2,3},lamp=TrafficLamp.YELLOW)  
    65.  @Deprecated  
    66.  @SuppressWarnings("")  
    67.  public void output()  
    68.  {  
    69.   System.out.println("output something!");  
    70.  }  
    71. }  
    72.  接著通過反射讀取註解的資訊:  
    73. public class MyReflection  
    74. {  
    75.  public static void main(String[] args) throws Exception  
    76.  {  
    77.   MyTest myTest = new MyTest();  
    78.     Class<MyTest> c = MyTest.class;  
    79.     Method method = c.getMethod("output", new Class[] {});  
    80.        //如果MyTest類名上有註解@MyAnnotation修飾,則為true  
    81.   if(MyTest.class.isAnnotationPresent(MyAnnotation.class))  
    82.   {  
    83.    System.out.println("have annotation");  
    84.   }  
    85.    if (method.isAnnotationPresent(MyAnnotation.class))  
    86.    {  
    87.    method.invoke(myTest, null); //調用output方法  
    88.    //擷取方法上註解@MyAnnotation的資訊  
    89.      MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);  
    90.     String hello = myAnnotation.hello();  
    91.    String world = myAnnotation.world();  
    92.    System.out.println(hello + ", " + world);//列印屬性hello和world的值  
    93.    System.out.println(myAnnotation.array().length);//列印屬性array數組的長度  
    94.    System.out.println(myAnnotation.lannotation().value()); //列印屬性lannotation的值  
    95.    System.out.println(myAnnotation.style());  
    96.    }  
    97.     //得到output方法上的所有註解,當然是被RetentionPolicy.RUNTIME修飾的  
    98.      Annotation[] annotations = method.getAnnotations();  
    99.       for (Annotation annotation : annotations)  
    100.   {  
    101.    System.out.println(annotation.annotationType().getName());  
    102.   }  
    103.    }  
    104. }  
    105. 上面程式列印:  
    106. have annotation  
    107. output something!  
    108. gege, shanghai  
    109. 3  
    110. baby  
    111. class java.lang.String  
    112. com.heima.annotation.MyAnnotation  
    113. java.lang.Deprecated  
    114.   
    115. 如果註解中有一個屬性名稱字叫value,則在應用時可以省略屬性名稱字不寫。  
    116. 可見,@Retention(RetentionPolicy.RUNTIME )註解中,RetentionPolicy.RUNTIME是註解屬性值,屬性名稱字是value,  
    117. 屬性的傳回型別是RetentionPolicy,如下:  
    118. public @interface MyTarget  
    119. {  
    120.     String value();  
    121. }  
    122. 可以這樣用:  
    123.   @MyTarget("aaa")  
    124.  public void doSomething()  
    125.  {  
    126.   System.out.println("hello world");  
    127.  }  
    128.    
    129. 註解@Target也是用來修飾註解的元註解,它有一個屬性ElementType也是枚舉類型,  
    130. 值為:ANNOTATION_TYPE CONSTRUCTOR  FIELD LOCAL_VARIABLE METHOD PACKAGE PARAMETER TYPE  
    131. 如@Target(ElementType.METHOD) 修飾的註解表示該註解只能用來修飾在方法上。  
    132. @Target(ElementType.METHOD)  
    133. @Retention(RetentionPolicy.RUNTIME)  
    134. public @interface MyTarget  
    135. {  
    136.  String value() default "hahaha";  
    137. }  
    138. 如把@MyTarget修飾在類上,則程式報錯,如:  
    139. @MyTarget  
    140. public class MyTargetTest  
    141. 註解大都用在開發架構中吧,好了有關註解就學習那麼多了,謝謝。  

Java注釋@interface的用法【轉】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.