简体   繁体   English

Java注释处理器,处理顺序

[英]Java Annotation Processor, Processing Order

I'm wondering if there is a way to process annotations from top down in a class, or at least in some deterministic order. 我想知道是否有一种方法可以在类中或至少以确定性顺序从上到下处理注释。

It doesn't seem like this is the case because the Processor class only provides: 看来情况并非如此,因为Processor类仅提供:

boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv);

Where the RoundEnvironment allows you to access a Set of annotated elements, eg: RoundEnvironment允许您访问一Set带注释的元素,例如:

Set<? extends Element>  getElementsAnnotatedWith(TypeElement a)

Everything is in terms of unordered collections, and this makes the order of processing unpredictable. 一切都取决于无序集合,这使得处理的顺序不可预测。 Is there anyway around this, besides trying to sort manually by element name or something? 除了尝试手动按元素名称或其他方式排序以外,还有其他解决方法吗?

As you have discovered, there is not a way to force processing of annotations in a specified order, using the current interfaces. 正如您所发现的那样,没有一种方法可以使用当前接口以指定顺序强制处理批注。

Here is a workaround. 这是一种解决方法。 Suppose that you wish to process every declaration annotation, such as annotations on fields and methods. 假设您希望处理每个声明注释,例如关于字段和方法的注释。 Don't register any callback for those declarations. 不要为这些声明注册任何回调。 Instead, invoke the annotation processor for every class. 而是为每个类调用注释处理器。 The annotation processor obtains the AST from javac, then walks it in the order you prefer. 注释处理器从javac获取AST,然后按照您喜欢的顺序进行遍历。 As an example, the Checker Framework uses this implementation strategy. 例如, Checker Framework使用此实现策略。

This workaround might not be sufficient for your needs, because it still processes each class in an arbitrary order -- for instance, one that depends on javac's staged compilation model. 这种变通办法可能不足以满足您的需要,因为它仍然以任意顺序处理每个类-例如,一个依赖于javac的分阶段编译模型的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM