注解的分類
按運行機制分:
源碼注解:只在源碼中存在,編譯后不存在
編譯時注解:源碼和編譯后的class文件都存在(如@Override,@Deprecated,@SuppressWarnings)
運行時注解:能在程序運行時起作用(如spring的依賴注入)
按來源分:
來自JDK的注解
第三方的注解
自定義的注解
自定義注解
如下實例給出了自定義注解的基本方法
1 package com.flypie.annotations; 2 3 import java.lang.annotation.Documented; 4 import java.lang.annotation.ElementType; 5 import java.lang.annotation.Inherited; 6 import java.lang.annotation.Retention; 7 import java.lang.annotation.RetentionPolicy; 8 import java.lang.annotation.Target; 9 10 /* @Target,@Retention,@Inherited,@Documented 11 * 這四個是對注解進行注解的元注解,負責自定義的注解的屬性 12 */ 13 @Target({ElementType.TYPE,ElementType.METHOD}) //表示注解的作用對象,ElementType.TYPE表示類,ElementType.METHOD表示方法 14 @Retention(RetentionPolicy.RUNTIME) //表示注解的保留機制,RetentionPolicy.RUNTIME表示運行時注解 15 @Inherited //表示該注解可繼承 16 @Documented //表示該注解可生成文檔 17 public @interface Design { 18 String author(); //注解成員,如果注解只有一個成員,則成員名必須為value(),成員類型只能為原始類型 19 int data() default 0; //注解成員,默認值為0 20 } 21
使用注解
1 package com.flypie; 2 3 import com.flypie.annotations.Design; 4 5 @Design(author="flypie",data=100) //使用自定義注解,有默認值的成員可以不用賦值,其余成員都要復值 6 public class Person { 7 @Design(author="flypie",data=90) 8 public void live(){ 9 10 } 11 }
解析java注解
1 package com.flypie; 2 3 import java.lang.annotation.Annotation; 4 import java.lang.reflect.Method; 5 6 import com.flypie.annotations.Design; 7 8 public class Main { 9 10 public static void main(String[] args) throws ClassNotFoundException { 11 12 Class c=Class.forName("com.flypie.Person"); //使用類加載器加載類 13 14 //1、找到類上的注解 15 if(c.isAnnotationPresent(Design.class)){ //判斷類是否被指定注解注解 16 Design d=(Design) c.getAnnotation(Design.class); //拿到類上的指定注解實例 17 System.out.println(d.data()); 18 } 19 20 //2、找到方法上的注解 21 Method[] ms=c.getMethods(); 22 for(Method m:ms){ 23 if(m.isAnnotationPresent(Design.class)){ //判斷方法是否被指定注解注解 24 Design d=m.getAnnotation(Design.class); //拿到類上的指定注解實例 25 System.out.println(d.data()); 26 } 27 } 28 29 //3、另外一種方法 30 for(Method m:ms){ 31 Annotation[] as=m.getAnnotations(); //拿到類上的注解集合 32 for(Annotation a:as){ 33 if(a instanceof Design){ //判斷指定注解 34 Design d=(Design) a; 35 System.out.println(d.data()); 36 } 37 } 38 } 39 } 40 41 }