public class Demo {
public Demo(){}
@Annotaion(name = "DemoClass::method1")
public void method1(params...)
{
}
}
我不想对“名称”属性进行硬编码,相反,我需要像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
}
}