在获取方法的参数注释时遇到麻烦,下面是一个易于测试的演示,欢迎向错误提出任何指导:
// 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);
}
}
Run Code Online (Sandbox Code Playgroud)
您不是在隐式设置Retention运行时,而是默认将@Retention (RetentionPolicy.CLASS)其表示为在类文件中表示,但在VM中不存在。要使其工作,请将其添加到您的界面:@Retention (RetentionPolicy.RUNTIME)作为类注释,然后再次工作!:D
在使用它时,您可能希望@Target仅针对参数而不是方法/字段/类等设置特定的参数。