package com.java.annotation;import java.lang.annotation.*;/** * Created by lw on 14-5-30. * 自訂註解 */@Documented@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface MethodInfo { public String Value() default "暫無說明";}/*四個定義註解時候的限定資料@Target(ElementType.TYPE) :介面、類、枚舉、註解@Target(ElementType.FIELD) :欄位、枚舉的常量@Target(ElementType.METHOD) :方法@Target(ElementType.PARAMETER) :方法參數@Target(ElementType.CONSTRUCTOR) :建構函式@Target(ElementType.LOCAL_VARIABLE) :局部變數@Target(ElementType.ANNOTATION_TYPE):註解@Target(ElementType.PACKAGE) :包@Retention(RetentionPolicy.SOURCE) :在源檔案中有效(即源檔案保留)@Retention(RetentionPolicy.CLASS) :在class檔案中有效(即class保留)@Retention(RetentionPolicy.RUNTIME) :在運行時有效(即運行時保留)@Inherited:說明子類可以繼承父類中的該註解@Document:說明該註解將被包含在javadoc中*/
package com.java.annotation;import java.lang.annotation.Annotation;import java.lang.reflect.Method;/** * Created by lw on 14-5-30. */public class Test { /** * 擷取註解參數 * * @param annotationClass 註解類 * @param annotationField 註解類欄位名稱 * @param aClass 使用註解的class名稱 * @param methodName 使用註解的方法名稱 * @throws Exception */ public static void getAnnotationPar(Class annotationClass, String annotationField, Class aClass, String methodName) throws Exception { Method aClassMethod = aClass.getMethod(methodName); Annotation annotation = aClassMethod.getAnnotation(annotationClass); Method method = annotation.getClass().getDeclaredMethod(annotationField); System.out.println(method.invoke(annotation)); } public static void main(String[] args) throws Exception { Test.getAnnotationPar(MethodInfo.class, "Value", Test2Annotation.class, "testMyAnnotation"); }}class Test2Annotation { @MethodInfo(Value = "自訂的註解@MethodInfo") public void testMyAnnotation() { }}
源碼:https://github.com/xiaohulu/util_xiaohulu/tree/master/src/com/java/annotation