JAVA 自訂註解及參數擷取__JAVA

來源:互聯網
上載者:User
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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.