public class Demo {
public Demo(){}
@Annotaion(name = "DemoClass::method1")
public void method1(params...)
{
}
}
我不想硬编码“name”属性,而是需要将其传递为类似 this.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
}
}
关于java - 如何将调用注释的类名和方法作为 "value"传递给注释属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60618811/