检索Java注释属性

Die*_*ias 38 java annotations

如何在带注释的方法上检索注释的值?

我有:

@myAnnotation(attribute1 = value1, attibute2 = value2)
public void myMethod()
{
  //I want to get value1 here
}
Run Code Online (Sandbox Code Playgroud)

Chs*_*y76 51

  1. 获得Method实例.
  2. 获取注释.
  3. 获取注释属性值.

就像是:

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

两件重要的事情:

  • 没有办法让目前的方法,如没有getMethod(),如的getClass().因此,访问其自己的注释的方法需要知道自己的名称.
  • 必须将注释的保留策略设置为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)

  • 有一种方法可以获得当前的方法.要么`Thread.currentThread().getStackTrace()[2] .getMethodName()`或`new Throwable().fillInStackTrace().getStackTrace()[0] .getMethodName()`应该这样做. (5认同)