如何在带注释的方法上检索注释的值?
我有:
@myAnnotation(attribute1 = value1, attibute2 = value2)
public void myMethod()
{
//I want to get value1 here
}
Run Code Online (Sandbox Code Playgroud)
Chs*_*y76 51
Method实例.就像是:
Method m = getClass().getMethod("myMethod");
MyAnnotation a = m.getAnnotation(MyAnnotation.class);
MyValueType value1 = a.attribute1();
Run Code Online (Sandbox Code Playgroud)
当然,您需要捕获/处理适当的异常.以上假设您确实从当前类中检索方法(替换getClass()为Class.forName()其他方法),并且该方法是公共的(getDeclaredMethods()如果不是这样,则使用)
mha*_*ler 22
两件重要的事情:
RUNTIME,以便您可以在运行时访问注释.默认值为compile-time,这意味着注释在类文件中可用,但在运行时无法使用反射进行访问.完整示例:
@Retention(RetentionPolicy.RUNTIME)
public static @interface MyAnnotation {
String value1();
int value2();
}
@Test
@MyAnnotation(value1 = "Foo", value2 = 1337)
public void testAnnotation() throws Exception {
Method[] methods = getClass().getMethods();
Method method = methods[0];
assertEquals("testAnnotation", method.getName());
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
assertEquals("Foo", annotation.value1());
assertEquals(1337, annotation.value2());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49541 次 |
| 最近记录: |