我在 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);
因此 MyAbstractProcessor.patches 将使用注释填充类列表。一个高尚的想法,除了这个 APT 在构建时而不是运行时执行的缺陷。
甚至可以在运行时使用 APT 吗?
还是我使用了错误的框架来获得我想要的东西?
最佳答案
您可以使用反射在运行时访问注释 - getAnnotations .
要使用您的注释获取类列表(在您的类路径中),您可以 - 在运行时 - 遍历所有类以测试它们是否具有该注释。
或者 - 在构建时 - 您可以使用类列表构建一个类。
关于java - 如何在运行时使用 Annotation Processing API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10241528/