我使用继承自 AbstractProcessor
的类中的方法 process()
来获取使用我的注释的元素的名称。
如何保存这些名称的列表,以便我可以在我的例如中使用它们。 main()
方法?
@edit 我有一个类 ClassList
,它将存储使用注释 @CustomAnnotation
public class ClassList {
private static final List<String> classList= new LinkedList<>();
public static List<String> getClassList() {
return classList;
}
public static void addList(String name) {
classList.add(name);
}
}
这里我有接口(interface)@CustomAnnotation
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation{
}
这是处理注释的类的实现
@SupportedAnnotationTypes("com.example.CustomAnnotation")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class CompileTimeAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(CustomAnnotation.class);
for (Element e : elements) {
//adds each name to the list
ClassList.addList(e.getSimpleName().toString());
}
//prints the array
System.out.println(Arrays.toString(ClassList.getClassList().toArray(new String[ClassList.getClassList().size()])));
return true;
}
}
然后我使用注释
@CustomAnnotation
public class AnnotatedClass {
}
@CustomAnnotation
public class TestClass {
}
现在,当我有了 main()
方法时,我想访问这些类。
public static void main(String[] args) {
System.out.println(ClassList.getClassList().size());
}
当我清理和构建时,它确实在方法 process()
中打印数组,但随后我运行主程序,列表为空。如何在主程序中访问该列表?
最佳答案
注释处理发生在编译时。您必须保留该信息直到运行时。唯一的方法是将其写入某些永久存储(例如应用程序资源)。
- 至少提供
RetentionPolycy.CLASS
注释,以防万一。 - 在每个编译轮次中,搜索新的带注释元素并将其名称添加到 Set 中,就像您已经做的那样(提示:存储
Name
实例同样有效)。 - 在最后一轮编译期间,将该 Set 的内容写入某个资源文件(您可以在 Google 的 Auto 库中找到生成资源文件的注释处理器示例)。
- 读取应用程序主方法中的资源文件
关于java - 如何保存使用我的注释的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36867422/