2014-09-23 31 views
2

所以我想学习使用自定义注释的基础,所以我已经创建了一个空的注释:为什么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,但我认为首先要做一个类级别的例子比较容易)。

回答

3

你需要注释的注释类像这样让你的注释信息可在运行时:

@Retention(RetentionPolicy.RUNTIME) 
public @interface CallMe { 

} 
2

尝试:

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.TYPE}) 
public @interface CallMe { 
... 
} 
+0

+1谢谢,目标也是有用的了解。 – FatalError 2014-09-23 17:22:44

相关问题