繁体   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