【发布时间】:2014-11-26 19:26:33
【问题描述】:
- 我想加载类(使用运行时注解),并检查注解的类型。
- 注释与字段相关。
-
该类不在类路径中,也不在 eclipse 项目中
- 对于这个问题,我需要用它的注解类来编译这个类。
我使用这个链接加载了这个类:
http://www.java2s.com/Tutorial/Java/0125__Reflection/URLclassloader.htm
加载类后,我尝试获取每个字段的注释并检查注释类型:
Field[] fields = obj.getClass().getFields();
for (Field field : fields) {
Annotation[] ann = field.getAnnotations();
for (Annotation annotation : ann) {
if (annotation.equals(Example.class)) {
System.out.println("Example annotation");
}
}
}
我希望看到打印的“示例注释”,但我没有得到它。
test.class和Example.class有如下java源码:
public class Test
{
@Example (size = 5)
public int x;
@Example (size = 3)
public int y;
}
public @interface Example
{
int size();
}
保存在不同分区的 2 个类,我用 javac 编译它们(并得到 2 个 .class 文件)
我读到: 1.Java - loading annotated classes 但没有得到解决方案。
那么我做错了什么? (为什么我能看到“示例注释”)? 谢谢
【问题讨论】:
标签: java reflection annotations