[英]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...)
{
}
}
I do not want to hardcode the "name" attribute, instead I need to pass it as something like this.getClass().getName().NAME_OF_THE_METHOD_ON_WHICH_INVOKED我不想对“name”属性进行硬编码,而是需要将它作为这样的东西传递。getClass().getName().NAME_OF_THE_METHOD_ON_WHICH_INVOKED
First, create a custom annotation一、创建自定义注解
@Retention(RetentionPolicy.RUNTIME)
@interface Annotation {
public int value1();
public int value2();
}
Then use it然后使用它
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.