定義註解與定義接口類似,只是比接口多了個@符號,可以在註解中定義方法,簡單例子如下:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Description @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Description { String value() default "no description"; }
它有以下特性:
1、註解方法不能有參數。
2、註解方法返回值類型侷限於原始類型,字符串,枚舉,註解或由這些類型組成的數組。
3、註解類型可以包含默認值,如上代碼中的 default "no description";
4、註解可以包含以下四種元註解:
@Documented – 使用該註解的元素將會被javadoc或類似工具文檔化,它應用於類型聲明,類型聲明的註解會影響客戶端對註解元素的使用。如果一個類型聲明添加了該註解,那麼它的註解會成爲被註解元素的公共API的一部分。
@Target – 表示支持的註解程序元素種類,可以是TYPE,METHOD,CONSTRUCTOR,FILED等等,如果不寫該註解表示不限制,可以使用在任何程序類型上。
@Inherited – 表示一個註解類型會被自動繼承,如果用戶在類聲明的時候查詢註解類型,同時類聲明中也沒有這個類型的註解,那麼註解類型會自動查詢該類的父類,這個過程將會不停地重複,直到該類型的註解被找到爲止,或是到達類結構的頂層(Object)。
@Retention – 表示註解類型保留時間長短,它接收RetentionPolicy參數,可能的值有SOURCE, CLASS, 以及RUNTIME。
入門實例:(參考網絡)
定義註解:
import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Name { String originate(); String community(); }
註解使用:
@Description(value = "JavaEyer,is better") public class JavaEyer { @Name(originate = "創始人:abc",community = "javaeye") public String getEyeName() { return null; } @Name(originate = "創始人:nba",community = "Americ") public String getSideName() { return "excuse me"; } }
測試類:
import com.sun.corba.se.impl.orbutil.concurrent.Sync; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; public class AnnotationTest { @SuppressWarnings("uncheked") public static void main(String[] args) { final String CLASS_NAME = "JavaEyer"; try { Class test = Class.forName(CLASS_NAME); Method[] methods = test.getMethods(); boolean flag = test.isAnnotationPresent(Description.class); if(flag){ Description des = (Description)test.getAnnotation(Description.class); System.out.println("描述:"+des.value()); System.out.println("----------------------------"); } Set<Method> set = new HashSet<Method>(); for(int i = 0;i<methods.length;i++){ boolean otherflag = methods[i].isAnnotationPresent(Name.class); if(otherflag){ set.add(methods[i]); } } for(Method method:set){ Name name = method.getAnnotation(Name.class); System.out.println(name.originate()); System.out.println("創建的社區:"+ name.community()); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } }