cor*_*ath 5 java apt annotations
我已经并遵循了Internet上的一些注释处理工具(APT)指南(例如1和2),并设法使其在编译器/构建时间中运行,甚至使其在Eclipse中运行。
有没有一种方法可以在运行时使用APT使用注释来获取类型(类)的列表。
我写了类似的东西:
@SupportedAnnotationTypes("com.domain.MyAnnotation")
public class MyAbstractProcessor extends AbstractProcessor {
public static Map<Element, MyAnnotation> patches = new HashMap<Element, MyAnnotation>();
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) {
// Get all classes that has the annotation
Set<? extends Element> classElements = roundEnvironment.getElementsAnnotatedWith(MyAnnotation.class);
// For each class that has the annotation
for (final Element classElement : classElements) {
patches.put(classElement, annotation);
Run Code Online (Sandbox Code Playgroud)
因此,将使用注释使用类列表填充MyAbstractProcessor.patches。除了此APT在构建时而非运行时执行的缺陷外,这是一个高尚的想法。
甚至可以在运行时使用APT吗?
还是我使用错误的框架来获取我想要的?
您可以在运行时使用反射 - getAnnotations访问注释。
要使用注释获取类列表(在您的类路径中),您可以 - 在运行时 - 遍历所有类,测试它们是否具有该注释。
或者 - 在构建时 - 您可以构建一个包含类列表的类。