如何以编程方式读取在Method的返回类型上定义的注释

时间:2015-01-22 12:07:01

标签: java reflection annotations

我们如何以编程方式读取在Method的返回类型上定义的注释?

我尝试在java.lang.reflect.Method中查找方法,但我只能找到读取返回值的类类型或读取通用信息的方法。是否有方法来读取注释?< / p>

考虑此方法定义: -

public class ABC {
      public static @MyAnnotation @AnotherAnnotation String main(String args[]) {

       return null;        
      }

所以我的问题是: - 我们可以读取返回类型String中定义的注释吗?

注释如下: -

MyAnnotation.java

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

    public String[] author() default {"Its me","Its me"};



}

AnotherAnnotation.java

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnotherAnnotation {

}

1 个答案:

答案 0 :(得分:1)

您似乎对注释的位置感到困惑:

public static @MyAnnotation @AnotherAnnotation String main(String args[])

这两个注释没有注释方法的返回类型。他们正在诠释方法本身。以上相当于

@MyAnnotation 
@AnotherAnnotation 
public static String main(String args[])

甚至

public @MyAnnotation @AnotherAnnotation static String main(String args[])

您可以使用getAnnotations()getDeclaredAnnotations()Method对象获取这些内容。