所以我想学习使用自定义注释的基础,所以我已经创建了一个空的注释:为什么java不能看到我的注释?
public @interface CallMe {
}
和Test
类:
import java.lang.annotation.*;
@CallMe
public class Test {
public static void main(String[] args) throws Exception {
Annotation[] annotations = Test.class.getAnnotations();
if (Test.class.isAnnotationPresent(CallMe.class)) {
System.out.println("CallMe is present.");
}
System.out.println("Found " + annotations.length + " annotations.");
for (Annotation a: annotations) {
System.out.println("Annotation: " + a);
}
}
}
我编译的类和执行Test
,但:
$ javac Test.java CallMe.java
$ java Test
Found 0 annotations.
我使用OpenJDK 1.6进行此测试,如果它很重要。我对.getAnnotations()
和.getDeclaredAnnotations()
都有好感,但没有结果。
为什么Java不能找到注释? (如果你想知道,我最初会尝试注释方法,这就是为什么我做了CallMe
,但我认为首先要做一个类级别的例子比较容易)。
+1谢谢,目标也是有用的了解。 – FatalError 2014-09-23 17:22:44