我如何将在其上作为“值”调用注释的类名和方法传递给注释属性

问题描述 投票:0回答:1
 public class Demo {

     public Demo(){}

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

     }

}

我不想对“名称”属性进行硬编码,相反,我需要像this.getClass()。getName()一样传递它。NAME_OF_THE_METHOD_ON_WHICH_INVOKED

java annotations
1个回答
0
投票

首先,创建自定义注释

@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
    } 
}
© www.soinside.com 2019 - 2024. All rights reserved.