java 註解使用
註解就相當於一個類,使用一個註解就相當於建立了註解類的一個例項物件
java內建註解,如
@Deprecated 意思是“廢棄的,過時的”
@Override 意思是“重寫、覆蓋”
@SuppressWarnings 意思是“壓縮警告”
註解(Annotation)相當於一種標記,javac編譯器、開發工具等根據反射來了解你的類、方法、屬性等元素是有具有標記,根據標記去做相應的事情。標記可以加在包、類、屬性、方法、方法的引數及區域性變數上。
註解就相當於一個你的源程式要呼叫一個類,在源程式中應用某個註解,得事先準備好這個註解類。就像你要呼叫某個類,得事先開發好這個類。
在一個註解類上使用另一個註解類,那麼被使用的註解類就稱為元註解。用來修飾自定義註解的Retention就是元註解,Retention有個RetentionPolicy型別的value();屬性,有三種取值
如果一個註解中有一個名稱為value的屬性,且你只想設定value屬性(即其他屬性都採用預設值或者你只有一個value屬性),那麼可以省略掉“value=”部分。例如@SuppressWarnings("deprecation")
RetentionPolicy.SOURCE,只在java原始檔中存在(.java),編譯後不存在。如果做一些檢查性的操作如@Override 和 @SuppressWarnings,使用此註解
RetentionPolicy.CLASS,註解被保留到.class檔案,,但jvm載入class檔案時候被遺棄,這是預設的生命週期;(很遺憾,儘管看了很多部落格我也沒搞清這個)
RetentionPolicy.RUNTIME,註解不僅被儲存到class檔案中,jvm載入class檔案之後,仍然存在;一般如果需要在執行時去動態獲取註解資訊,那隻能用 RUNTIME 註解,比如@Deprecated使用RUNTIME註解
綜合示例:
MyAnnotation註解:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention;View Codeimport java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE,ElementType.METHOD})//target註解決定MyAnnotation註解可以加到哪些成分上 @Retention(RetentionPolicy.RUNTIME)//Retention註解決定MyAnnotation註解的生命週期 public @interface MyAnnotation { String color() default "blue";//定義基本屬性,並指定預設值 String value();//定義一個名稱為value的屬性。value是特殊的基本屬性 int[] arr() default {1,2,3};//定義一個數組型別的屬性 ColorEnum clor() default ColorEnum.RED;//列舉型別的屬性並指定預設值 MetaAnnotation authorName() default @MetaAnnotation("yanan");//MyAnnotation註解裡使用MetaAnnotation註解,MetaAnnotation就被成為元註解 }
MetaAnnotation註解:
/** * TODO 做為元註解用 * 2020年8月5日 * @author zhangyanan */ public @interface MetaAnnotation { String value();//設定特殊屬性value }View Code
ColorEnum列舉:
/** * TODO 列舉型別的顏色 * 2020年8月5日 * @author zhangyanan */ public enum ColorEnum { RED,BLUE,BLACK,YELLOW,WHITE,PINK }View Code
TestAnnotation測試類:
@MyAnnotation("zyn")//此處的zyn是對MyAnnotation特殊屬性value的賦值 public class TestAnnotation { public static void main(String[] args) { //利用反射檢查TestAnnotation類是否有註解 if(TestAnnotation.class.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation annotation = TestAnnotation.class.getAnnotation(MyAnnotation.class); System.out.println(annotation.color()); System.out.println(annotation.value()); System.out.println(annotation.clor()); System.out.println(annotation.arr()[2]); System.out.println(annotation.authorName().value()); }else{ System.out.println("TestAnnotation類沒有MyAnnotation註解"); } } }View Code