首页 > 解决方案 > 如何将调用注释的类名和方法作为“值”传递给注释属性

问题描述

 public class Demo {

     public Demo(){}

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

     }

}

我不想硬编码“名称”属性,而是需要将其作为类似 this.getClass().getName().NAME_OF_THE_METHOD_ON_WHICH_INVOKED 的内容传递

标签: javaannotations

解决方案


一、创建自定义注解

@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
    } 
}

推荐阅读