java 註解 補17號沒有整理筆記
註解
註解的作用
早期專案配置檔案過多,專案複雜度高,維護成本高,更新迭代麻煩
中期:使用註解減少配置檔案
now : 註解+配置檔案
註解用來記錄資料,通過反射的方式在程式碼執行過程中獲得這些資料,減少配置檔案
支援的資料型別
8中基本資料型別 類型別 字串 列舉 及以上1種對應的陣列
int a1(); //int 型別的註解
int [] a11(); //對應陣列型別的註解
String b1(); //字串型別的註解
Class<?> class();
public enum Week{ //宣告一個列舉
mon,sun,sat...
}
Week week(); //引用列舉型別
Week [] week();
構造
寫一個註解: 註解可以用於屬性 方法 構造方法 靜態方法
public @interface an1{
}
元註解
四類註解註解的註解
@Target(elementype.*) 用於規範註解使用的位置;
@Retention (retentionpolicy.*) 規範註解的儲存位置 :二進位制程式碼中,程式碼中,執行中?
預設不寫為class,表示需要通過反射獲取;
source 表示在原檔案中保留此註解
runtime 表示在執行過程中保留此註解
@Inherited 表示此註解將被子類繼承 :加了該註解的類的子類自動新增此註解;
@Documented 表示在文件註釋中保留此註解;
註解的屬性名,如果為value,可以直接寫值,否則都要寫為name=value 形式;
@Taeget(ElementType.Method) public @interface an1{ String str() } @Taeget(ElementType.Method) public @interface an2{ String value() } public class test{ @an2(value ="abs") //或者: @an2("abs") void m1(); @an1(str="abs") //這裡不能使用@an1("abs") void m1(); }
獲取註解資訊(反射)
1.必填項:註解中三個屬性,使用default預設值,在使用註解時必須給其賦值;
//定義一個註解 public @interface an1{ String a(); String b(); } //在類上和方法上宣告這個註解 @an1 (a="A",b="B") public class test{ @an1 (a="a",b="b") private String name(); }
2.用Class.forname("全限定名")獲取類資訊可以得到宣告在對應的類上的註解物件,.
但不能獲取到屬性、方法上的資訊(註解的資訊);
Class<?> testclass =Class.forname("pacakge.xclass")
3.對類物件使用 .getannotation( "某註解.class") 獲取一個註解型別的物件
//獲取註解物件 an1 annotation = testclass.getannotation(an1.class); //呼叫註解物件的方法獲取對應方法可以get的註解資訊 system.out.print(annotation.a()+annotation.b()); //得到類上的註解資訊 A B
4.通過類物件獲取屬性,再通過屬性獲取宣告在屬性上的註解的資訊
Field fieldname =testclass.getdfield("name") //獲取name屬性 這裡是私有屬性,應該使用getdeclaredfield !!!!markdown手敲麻煩沒有敲~~ an1 annotation2 =fieldname.getannotation(an1.class);//獲取屬性上宣告的註解 system.out.print(annotation2.a()+annotation2.b())//得到 a b
5.獲取方法/構造方法上的註解類似,略;
使用註解
.....................待續;