简体   繁体   English

检索Java注释属性

[英]Retrieve Java Annotation Attribute

How can I retrieve the value of an annotation on the annotated method?? 如何在带注释的方法上检索注释的值?

I have: 我有:

@myAnnotation(attribute1 = value1, attibute2 = value2)
public void myMethod()
{
  //I want to get value1 here
}
  1. Obtain Method instance. 获取Method实例。
  2. Obtain annotation. 获取注释。
  3. Obtain annotation attribute value. 获取注释属性值。

Something like: 就像是:

Method m = getClass().getMethod("myMethod");
MyAnnotation a = m.getAnnotation(MyAnnotation.class);
MyValueType value1 = a.attribute1();

You'll need to catch / handle the appropriate exceptions, of course. 当然,您需要捕获/处理适当的异常。 The above assumes you are indeed retrieving method from the current class (replace getClass() with Class.forName() otherwise) and the method in question is public (use getDeclaredMethods() if that's not the case) 上面假设您确实从当前类中检索方法Class.forName()否则用Class.forName()替换getClass() )并且所讨论的方法是public(如果不是这样,请使用getDeclaredMethods()

Two important things: 两件重要的事情:

  • There is no way to get the current method , eg there is no getMethod() such as getClass(). 无法获取当前方法 ,例如没有getMethod(),例如getClass()。 Therefore, the method accessing its own annotation would need to know its own name. 因此,访问其自己的注释的方法需要知道自己的名称。
  • The retention policy of the annotation must be set to RUNTIME , so you can access the annotation at runtime. 注释的保留策略必须设置为RUNTIME ,因此您可以在运行时访问注释。 The default is compile-time, which means annotations are available in the class file, but cannot be accessed at runtime using reflection. 默认值为compile-time,这意味着注释在类文件中可用,但在运行时无法使用反射进行访问。

Full example: 完整示例:

@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());
}

要获取当前方法,请尝试使用以下代码:

Thread.currentThread().getStackTrace()[1].getClassName().toString()+\".\"+Thread.currentThread().getStackTrace()[1].getMethodName().toString()

@mhaller: a bit too long for a comment on your post. @mhaller:对你的帖子发表评论有点太长了。 Obviously would need further refinement to deal with overloaded methods, but it is not impossible.: 显然需要进一步细化来处理重载方法,但这并非不可能:

import java.lang.reflect.Method;

public class Hack {
    public static void main (String[] args) {
        (new Hack()).foobar();
    }
    public void foobar () {
        Method here = getCurrentMethod(this);
        System.out.format("And here we are: %s\n", here);
    }
    public static final Method getCurrentMethod(Object o) {
        String s = Thread.currentThread().getStackTrace()[2].getMethodName();
        Method cm = null;
        for(Method m : o.getClass().getMethods()){
            if(m.getName().equals(s)){
                cm = m; break;
            }
        }
        return cm;
    }
}

[edit: credit/thanks to Alexandr Priymak for spotting the error in main()] [编辑:感谢/感谢Alexandr Priymak发现main()中的错误]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM