最近一直在看aop,apt,Javassist之類的東西。看的自己是一臉懵逼,只能說,android世界太大,自己太渺小,知識稍微懂了那麽一些,還有很多遺落在那邊,還沒有理解完全。待我哪天開個天眼,再拿出來講講。
這次,主要講講這其中的註解。通過註解,aop可以很方便的切入一段代碼。
元註解
雲註解的作用就是負責註解其他註解。java5.0的時候,定義了4個標準的meta-annotation類型,它們用來提供對其他註解的類型作說明。1.@Target 2.@Retention 3.@Documented 4.@Inherited
@Target: 規定Annotation所修飾的對象範圍。有以下幾種 1.ElementType.CONSTRUCTOR ; 構造器聲明 2.ElementType.FIELD:成員變量、對象、屬性(包括enum實例) 3.ElementType.LOCAL_VARIABLE; 局部變量聲明 4.ElementType.METHOD ; 方法聲明 5.ElementType.package; 包聲明 6.ElementType.PARAMETER;參數聲明 7.ElementType.TYPE; 類、接口(包括註解類型)或enum聲明 示例: @Target(ElementType.TYPE) public @interface Table{ public String value() default ""; } @Target還支持填寫數組,同時支持多種範圍 @Target({ElementType.TYPE,ElementType.FIELD}) public @interface Test{}
@Retention:對Annotation的生命周期限制:某些Annotation僅出現在源代碼中,而被編譯器丟棄;而另一些卻被編譯在class文件中;編譯在class文件中的Annotation可能會被虛擬機忽略,而另一些在class被裝載時將被讀取。 1.RetentionPolicy.SOUREC: 在源文件中有效 2.RetentionPolicy.CLASS; 在class文件中有效 3.RetentionPolicy.RUNTIME;在運行時有效
示例:
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Column{ public String name() default ""
}
@Documented: 用於描述其它類型的annotation應該被作為被標註的程序成員的公共API,因此可以被例如javadoc此類的工具文檔化。Documented是一個標記註解,沒有成員 示例 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Column{ public String name() default ""; }
@Inherited: 是一個標記註解,@Inherited闡述了某個被標註的類型是被繼承的。如果一個使用了@Inherited修飾的annotation類型被用於一個class,則這個annotation將用於該class的子類。 示例: @Inherited public @interface Season{
public enum Sea{Spring,Summer,Autumn,Winter}; Sea sea() default Sea.Spring; }
當然了,我們也是可以自定義註解的。
在使用@interface自定義註解時,自動繼承了java.lang.annotation.Annotation接口。
@Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Description { public String value(); //只有一個參數的時候,必須為value }類的支持註解如下:
@Description("這是類上的註解") public class Person { public String getName(){ return ""; } }方法的支持註解如下:
public class Coder extends Person{ @Override @Description("這是方法上的註解") public String getName() { // TODO Auto-generated method stub return "Mark"; } }@Inherited表示可以繼承的 然後下面的這段代碼就是註解的解析了,通過反射來拿到哪些註解
public static void main(String[] args) { // TODO Auto-generated method stub //1.使用類加載器加載類 try { Class c=Class.forName("com.annotation.Coder"); //2.找到類加載器上面的註解 boolean isExist=c.isAnnotationPresent(Description.class); if(isExist){ //3 拿到註解實例 Description d=(Description) c.getAnnotation(Description.class); system.out.println(d.value()); } //4.找到方法上的註解 Method[] ms=c.getMethods(); for(Method m:ms){ boolean isMExist =m.isAnnotationPresent(Description.class); if(isMExist){ Description d=m.getAnnotation(Description.class); System.out.println(d.value()); } } } catch (Exception e) { // TODO: handle exception } }ok~ 這就是完整的註解了,如有不懂,歡迎留言。 當然了,最大的同誌交友網站,可以follow下我,時刻關註。https://github.com/zhairui
Tags: interface android default 源代碼 public
文章來源: