在 javax.annotation.processing
包有接口(interface)Processor
其中有一个功能:
/**
* Processes a set of annotation types on type elements
* originating from the prior round and returns whether or not
* these annotation types are claimed by this processor. If {@code
* true} is returned, the annotation types are claimed and subsequent
* processors will not be asked to process them; if {@code false}
* is returned, the annotation types are unclaimed and subsequent
* processors may be asked to process them. A processor may
* always return the same boolean value or may vary the result
* based on chosen criteria.
*
* <p>The input set will be empty if the processor supports {@code
* "*"} and the root elements have no annotations. A {@code
* Processor} must gracefully handle an empty set of annotations.
*
* @param annotations the annotation types requested to be processed
* @param roundEnv environment for information about the current and prior round
* @return whether or not the set of annotation types are claimed by this processor
*/
boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv);
Java API
AbstractProcessor
实现上述接口(interface)。现在我创建了自己的处理器类:public class MyProcessor extends AbstractProcessor {
...
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (TypeElement annotation: annotations) {
// How can I get the class of the annotation ?
}
}
}
我的问题:
annotations
在处理函数中是the the annotation types requested to be processed
那么,为什么是类型
TypeElement
不是 java.lang.annotation.Annotation
?我对此感到困惑,因为我不确定 annotations
实际上是指被注释的元素或真正的注释注释元素。TypeElement
中获取每个注释的类? 最佳答案
有包 javax.lang.model
它遵循 Mirrors: Design Principles for Meta-level Facilities of
Object-Oriented Programming Languages 中描述的基于镜像的设计.它是在(但不限于)注释处理框架中使用的经过精心设计的抽象。
Then, why is it with type
TypeElement
notjava.lang.annotation.Annotation
?
设计框架时,保留它很重要open (可扩展)。你永远不知道该语言的 future 版本会带来什么。假设可能出现新形式的元数据,您需要保持灵 active 。
I get confused by this because I am not sure whether the annotations actually mean the elements that being annotated or the real annotations annotating elements.
因为您正在处理注释类型,所以它是“真正的注释元素”。
for (TypeElement typeElement : annotations) {
// it's likely the ElementKind.ANNOTATION_TYPE
typeElement.getKind();
// elements annotated with the annotation
environment.getElementsAnnotatedWith(typeElement);
}
Because of my 1st question above, how can I get each annotation's class from the
TypeElement
?
TypeElement
代表您的注释类。 读书:
Processor
等核心类, AnnotatedConstruct
, Element
, TypeElement
, TypeMirror
. 关于java - 关于Processor接口(interface)的process(...)方法中定义的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58082423/