註解(Annotation),註解annotation
入門註解,英文叫做Annotation。是和枚舉,類,介面類似的包成員概念。之所以每個註解都加一個@字元,是因為在英文中,@=at,而AT正好是Annotation中的兩個字母,所以@就直接當做Annotation的縮寫了。 java.lang包提供了三個基本註解,如下:@SuppressWarings@SuppressWarings註解,表示不對指定的問題進行警告。用法如下:
public class AnnotationTest {@SuppressWarnings("deprecation")//deprecation表示廢棄,此行表示不對廢棄的方法警告public static void main(String[] args) {System.runFinalizersOnExit(true);}}上面代碼片中的第2行,表示不對廢棄的方法進行警告。runFinalizersOnExit()是廢棄的方法(表示方法已淘汰,但為了相容老代碼而保留),不加註解情況下,在MyEclipse中會在方法名字上顯示中劃線,在調用方法的行上會顯示警告圖示。用jdk的javac編譯,會給出警告。但是加了@SuppressWarings註解後,MyEclipse會去掉中劃線,javac編譯後也不會顯示警告。@Deprecated@Deprecated註解,表示下面的方法被廢棄。用法如下:
public class AnnotationTest {public static void main(String[] args) {sayHello();}@Deprecated//Deprecated單詞表示被廢棄的,此行代碼錶示sayHello方法已被廢棄public static void sayHello(){System.out.println("Hello world!");}}@Override@Override註解,表示下面的方法是重寫父類的方法,如果沒重寫成功,編譯會報錯。樣本如下:
public class ReflectPoint {int x;int y;public ReflectPoint(int x,int y) {this.x=x;this.y=y;System.out.println(this.hashCode());}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + x;result = prime * result + y;return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;ReflectPoint other = (ReflectPoint) obj;if (x != other.x)return false;if (y != other.y)return false;return true;}}上面的代碼中@Overrider表示緊接著的方法是重寫父類的方法,相當於告訴編譯器,如果下面的方法不是重寫父類的方法,請報錯,這樣
可以防止參數類型沒寫準確而沒有成功的重寫父類的方法的問題。
註解的定義與反射調用在MyEclipse中建立一個註解類很簡單,只需在包上右擊,選擇New→Annotation, 這樣就建好了一個基本的註解,如下:
public @interface MyAnnotation {}可見@interface就是定義註解的關鍵詞。由此可見註解時一種特殊的介面。然後讓我們試試反射註解
@MyAnnotationpublic class AnnotationTest {public static void main(String[] args) {//檢查AnnotationTest類上是否有MyAnnotation註解if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){//擷取AnnotationTest類的MyAnnotation註解MyAnnotation annotation=(MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class);System.out.println(annotation);}}}上面的代碼運行後什麼也不會輸出,別急,因為出現這種情況是因為註解缺少東西。@Retention@Retention註解用於指定下面的註解的生命週期。它的唯一參數有三個取值:RetetionPolicy.SOURCE:表示指定的註解只在.java源檔案中起作用,這個註解不會被編譯進jar包RetetionPolicy.CLASS:表示指定的註解會被編譯進jar包,但是不能被反射。這個是預設值。RetetionPolicy.RUNTIME:表示註解會連同宿主類被載入進記憶體,只有定義註解時,指定了這個參數,註解才能被反射。另外@Retention是加在註解上的註解,這種註解叫
元註解反射註解接著上面的代碼,將註解定義改為如下:
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {}然後再運行下面的反射代碼:
@MyAnnotationpublic class AnnotationTest {public static void main(String[] args) {//檢查AnnotationTest類上是否有MyAnnotation註解if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){//擷取AnnotationTest類的MyAnnotation註解MyAnnotation annotation=(MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class);System.out.println(annotation);}}}輸出結果@cn.itcase.day2.MyAnnotation(),其中cn.itcase.day2是包名@Target@Target用於指定註解的作用對象,唯一參數的可能值是:ElementType.METHOD:表示只能只能作用於方法。ElementType.TYPE:表示只能作用於與類平級的類型,如類、介面、註解、枚舉ElementType.FIELD:表示只能作用於欄位聲明用法樣本如下:
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface MyAnnotation {}如果需要給Target加多個參數則需這麼寫@Target({ElementType.METHOD,ElementType.TYPE})
為註解增加‘屬性’由於註解的本質是個介面,所以註解的‘屬性’就是介面的方法。簡單的例子如下:
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})public @interface MyAnnotation {String color();}上面的代碼為MyAnnotation註解增加了一個屬性color,這樣就可以在調用註解的地方制定這個屬性。如下:
@MyAnnotation(color="blue")public class AnnotationTest {public static void main(String[] args) {//檢查AnnotationTest類上是否有MyAnnotation註解if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){//擷取AnnotationTest類的MyAnnotation註解MyAnnotation annotation=(MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class);System.out.println(annotation);System.out.println(annotation.color());}}}還可以為註解制定預設值,如下:
public @interface MyAnnotation {String color() default "blue";}這樣調用註解時,就可以不寫參數,如下:@MyAnnotation()或@MyAnnotation註解還有一個特殊的屬性value,定義方法如下:
public @interface MyAnnotation {String color() default "blue";String value();}這時就可以這樣調用註解
@MyAnnotation("Hello")注意到value的特殊之處是可以不寫屬性名稱,而其他屬性在調用賦值時,都必須寫屬性名稱。
註解的屬性可以使任意資料類型,下面用資料舉例:
public @interface MyAnnotation {String color() default "blue";String value();int[] arrayAttr() default {1,2,3}; }調用方法如下:@MyAnnotation(color="blue",value="Hello",arrayAttr={2,1,3})或@MyAnnotation("Hello")
但是@MyAnnotation("Hello",arrayAttr={2,1,3})的寫法是錯誤,註解的參數要麼全寫屬性名稱,要麼全不寫,不能混搭
枚舉類型屬性在註解中定義枚舉類型屬性的方法如下:
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})public @interface MyAnnotation {EnumDemo.TrafficLamp lamp() default EnumDemo.TrafficLamp.GREEN;}其中的枚舉EnumDemo.TrafficLamp源碼如下:
public class EnumDemo {/** * 交通燈枚舉 * @author programBoy */public enum TrafficLamp{GREEN{public TrafficLamp getNext() {return YELLOW;}},RED{public TrafficLamp getNext() {return GREEN;}},YELLOW{public TrafficLamp getNext() {return RED;}};public abstract TrafficLamp getNext();}}然後調用註解,並反射註解,進行測試,代碼如下:
@MyAnnotationpublic class AnnotationTest {public static void main(String[] args) {//檢查AnnotationTest類上是否有MyAnnotation註解if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){//擷取AnnotationTest類的MyAnnotation註解MyAnnotation annotation=(MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class);System.out.println(annotation);System.out.println(annotation.lamp().getNext().name());}}}由於註解的屬性lamp有預設值,所以此處不用寫此參數。運行上面的代碼,結果如下:@cn.itcase.day2.MyAnnotation(lamp=GREEN)
YELLOW可見lamp屬性在編譯時間被加上了預設值,只是原始碼不用寫而已註解類型屬性
首先再定義一個註解,如下:
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)public @interface AttrAnnotation {//注意此處必須加public,否則反射不出來String value();}
然後在MyAnnotation註解裡定義一個註解類型的屬性,如下:
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})public @interface MyAnnotation {AttrAnnotation annotationAttribute() default @AttrAnnotation("Hello"); //當註解被當做類型使用時,不需要加@符號,當註解需要被執行個體化時,才需要加@符號。}然後調用MyAnnotation註解,並反射其中的註解屬性:
@MyAnnotation(annotationAttribute=@AttrAnnotation("雷軍"))public class AnnotationTest {public static void main(String[] args) {//檢查AnnotationTest類上是否有MyAnnotation註解if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){//擷取AnnotationTest類的MyAnnotation註解MyAnnotation annotation=(MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class);System.out.println(annotation);System.out.println(annotation.annotationAttribute().value());}}}該程式運行結果如下:
@cn.itcase.day2.MyAnnotation(annotationAttribute=@cn.itcase.day2.AttrAnnotation(value=雷軍))
雷軍