Java - 参数注释

Java - Parameter annotations

无法获取方法的参数注释,下面是一个易于测试的演示,欢迎任何有关错误的指导:

// Annotation
public @interface At {}

// Class
public class AnnoTest {

   public void myTest(@At String myVar1, String myVar2){}
}

// Test
public class App {

    public static void main(String[] args) {

        Class myClass = AnnoTest.class;

        Method method = myClass.getMethods()[0];
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();

        // Should output 1 instead of 0
        System.out.println(parameterAnnotations[0].length);
    }
}

您没有将 Retention 隐式设置为运行时,这样它默认为 @Retention (RetentionPolicy.CLASS) 这表示它在 class 文件中表示但不存在于 VM 中。为了让它工作,将它添加到你的界面:@Retention (RetentionPolicy.RUNTIME) as class annotatio,然后它再次工作! :D

当您这样做时,您可能希望将特定的 @Target 设置为仅参数而不是 methods/fields/classes 等

默认情况下,注释由编译器记录在 class 文件中,但不需要由 VM 在 运行 时保留(正在应用 RetentionPolicy.CLASS 保留策略)。

要更改注释的保留时间,您可以使用 Retention 元注释。

在你的情况下,你想让它可以反射地阅读所以你需要它必须使用RetentionPolicy.RUNTIME在class中记录注释文件,但仍由 VM 在 运行 时间保留。

@Retention(RetentionPolicy.RUNTIME)
public @interface At {}

我还建议您指明注释类型 At 适用的程序元素。

在你的例子中,参数注释应该是

 @Target(ElementType.PARAMETER)

这样编译器将强制执行指定的使用限制。

默认情况下,声明的类型可用于任何程序元素:

  • ANNOTATION_TYPE - Annotation type declaration
  • CONSTRUCTOR - Constructor declaration
  • FIELD - Field declaration (includes enum constants)
  • LOCAL_VARIABLE - Local variable declaration
  • METHOD - Method declaration
  • PACKAGE - Package declaration
  • PARAMETER - Parameter declaration
  • TYPE - Class, interface (including annotation type), or enum declaration