О параметре, определенном в методе process (...) интерфейса Processor - PullRequest
3 голосов
/ 24 сентября 2019

В пакете javax.annotation.processing есть интерфейс 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 реализует вышеуказанный интерфейс.Теперь я создал свой собственный класс процессора:

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 ?
        }
    }
}

Мои вопросы:

  1. Документ API сообщает, что annotations в функции процесса:

типы аннотаций, запрашиваемые для обработки

Тогда, почему это с типом TypeElement, а не java.lang.annotation.Annotation?Меня это смущает, потому что я не уверен, что на самом деле annotations означает элементы, которые аннотируются, или реальные аннотации, аннотирующие элементы.

Из-за моего первого вопроса выше, как я могу получить класс каждой аннотации из TypeElement?

1 Ответ

2 голосов
/ 26 сентября 2019

Существует пакет javax.lang.model, который следует зеркальному дизайну, описанному в Зеркала: принципы проектирования для метауровневых средств объектно-ориентированных языков программирования .Это очень продуманная абстракция, используемая (но не ограничиваясь этим) средой обработки аннотаций.

  1. Тогда почему она имеет тип TypeElement, а не java.lang.annotation.Annotation?

    Когда вы разрабатываете фреймворк, важно держать его открытым (доступно для расширения).Вы никогда не знаете, что принесут будущие версии языка.Вы должны сохранять гибкость, предполагая, что может появиться новая форма метаданных.

    Меня смущает это, потому что я не уверен, действительно ли аннотации означают элементы, которые аннотируются, или настоящие аннотации, аннотирующие элементы.

    Это «реальные аннотации, аннотирующие элементы», так как вы обрабатываете типы аннотаций.

    for (TypeElement typeElement : annotations) {
        // it's likely the ElementKind.ANNOTATION_TYPE
        typeElement.getKind();
    
        // elements annotated with the annotation
        environment.getElementsAnnotatedWith(typeElement);
    }
    
  2. Из-за моего 1-го вопроса выше, какя могу получить класс каждой аннотации из TypeElement?

    TypeElement представляет ваш класс аннотаций.

Для чтения:

  1. https://bracha.org/mirrors.pdf (обработка займет много времени)

  2. https://www.baeldung.com/java-annotation-processing-builder (этопростой процессор аннотаций)

  3. https://github.com/rzwitserloot/lombok/blob/master/src/core/lombok/core/AnnotationProcessor.java (это хороший практический пример)

  4. Javadoc пакет и основные классы, такие как Processor, AnnotatedConstruct, Element, TypeElement, TypeMirror.

...