簡體   English   中英

如何將作為“值”調用注釋的類名和方法傳遞給注釋屬性

[英]How can I pass the class name and method on which the annotaion being invoked as a "value" to the annotation attribute

 public class Demo {

     public Demo(){}

     @Annotaion(name = "DemoClass::method1")
     public void method1(params...)
     {

     }

}

我不想對“name”屬性進行硬編碼,而是需要將它作為這樣的東西傳遞。getClass().getName().NAME_OF_THE_METHOD_ON_WHICH_INVOKED

一、創建自定義注解

@Retention(RetentionPolicy.RUNTIME) 
@interface Annotation { 
    public int value1(); 
    public int value2(); 
} 

然后使用它

public class TestClass {
    @Annotation(value1 = 15, value2 = 30) 
    public static void test(){ 
            Class cl = TestClass.class; 
            Method[] allMethods = cl.getMethods(); 
            Method thisMethod = null;

            for (Method m : allMethods)
                if (m.getName().equals("test")) thisMethod = m; 


            Annotation a = thisMethod.getAnnotation(Annotation.class); 
            a.value1(); //returns 15
            a.value2(); //returns 30
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM