Java:获取私有成员的注释
我试图找到所有用自定义注释注释的字段,但它似乎没有检测到它。相同的代码适用于标准注释,例如@Deprecated。
重现的最少代码:
public class MyClass {
public @interface MyAnnotation {}
@MyAnnotation Object someObject;
@MyAnnotation @Deprecated Object someDeprecatedObject;
@Deprecated Object aThirdObject;
public static void main(String[] args) {
Class<?> cls = MyClass.class;
for (Field field : cls.getDeclaredFields()) {
System.out.print(field.getName());
for (Annotation a : field.getDeclaredAnnotations())
System.out.print(" " + a);
System.out.println();
}
}
}
输出:
someObject
someDeprecatedObject @java.lang.Deprecated()
aThirdObject @java.lang.Deprecated()
@Deprecated 出现,但 @MyAnnotation 没有!帮助!
I'm trying to find all fields annotated with a custom annotation, but it doesn't seem to detect it. The same code works fine for standard annotations, such as @Deprecated.
Minimal code to reproduce:
public class MyClass {
public @interface MyAnnotation {}
@MyAnnotation Object someObject;
@MyAnnotation @Deprecated Object someDeprecatedObject;
@Deprecated Object aThirdObject;
public static void main(String[] args) {
Class<?> cls = MyClass.class;
for (Field field : cls.getDeclaredFields()) {
System.out.print(field.getName());
for (Annotation a : field.getDeclaredAnnotations())
System.out.print(" " + a);
System.out.println();
}
}
}
Output:
someObject
someDeprecatedObject @java.lang.Deprecated()
aThirdObject @java.lang.Deprecated()
@Deprecated comes up, but @MyAnnotation doesn't! Help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,注释不会在运行时保留,因此无法反映。您需要像这样声明注释以确保它在运行时存在:
By default, annotations are not kept at runtime and so cannot be reflected upon. You need to declare your annotation like this to ensure it exists at runtime: