glm*_*ndr 26 java reflection annotations
这是一个测试类:
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class TestAnnotations {
@interface Annotate{}
@Annotate public void myMethod(){}
public static void main(String[] args) {
try{
Method[] methods = TestAnnotations.class.getDeclaredMethods();
Method m = methods[1];
assert m.getName().equals("myMethod");
System.out.println("method inspected ? " + m.getName());
Annotation a = m.getAnnotation(Annotate.class);
System.out.println("annotation ? " + a);
System.out.println("annotations length ? "
+ m.getDeclaredAnnotations().length);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的输出:
method inspected ? myMethod
annotation : null
annotations length : 0
Run Code Online (Sandbox Code Playgroud)
我错过了通过反思使注释可见?
我是否需要一个注释处理器,即使只是检查它们的存在?
aby*_*byx 39
为了在运行时访问注释,它需要具有Runtime的保留策略.
@Retention(RetentionPolicy.RUNTIME) @interface Annotate {}
Run Code Online (Sandbox Code Playgroud)
否则,将删除注释并且JVM不会识别它们.
有关更多信息,请参阅此处.