我正在尝试使用反射和注释.出于某种原因,每当我向字段(或类或方法)添加注释,并使用反射来查看字段时,我看到它的annotations字段为空.
例如,这段代码:
public class Test {
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
System.out.println(Test.class.getField("bl").getAnnotations().length);
}
@anno
public int bl;
public @interface anno {}
}
Run Code Online (Sandbox Code Playgroud)
打印0.
顺便说一句,Java一般不会忽略注释,并且(例如)我使用@Deprecated注释时 - Eclipse会识别它并告诉我该类已被弃用.
我正在使用Eclipse Indigo和Java SE Development Kit 7更新2.谢谢!
ska*_*man 23
默认情况下,注释不可用于反射.为此,您需要更改保留策略,即
@Retention(RetentionPolicy.RUNTIME)
public @interface Anno {}
Run Code Online (Sandbox Code Playgroud)
可以在Javadoc中找到各种保留策略.默认(出于神秘的原因,似乎没有人知道)是CLASS.
我会检查@Retention 例如
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Deprecated {
}
Run Code Online (Sandbox Code Playgroud)
如果不设置它,它将在运行时不可见。
| 归档时间: |
|
| 查看次数: |
1483 次 |
| 最近记录: |