Abstract - Reading an element value during assembly

Is it possible to read the value of an annotation element at build time ? For example, if I have the following annotation:

public @interface State { String stage(); } 

and I annotate the method in the class, for example:

 public class Foo { @State(stage = "build") public String doSomething() { return "doing something"; } } 

How can I read the value of the annotation element of the @State element during assembly in the annotation processor? I have a processor built as follows:

 @SupportedAnnotationTypes(value = {"State"}) @SupportedSourceVersion(SourceVersion.RELEASE_6) public class StageProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> elementTypes, RoundEnvironment roundEnv) { for (Element element : roundEnv.getRootElements()) { // ... logic to read the value of element 'stage' from // annotation 'State' in here. } return true; } } 
+6
source share
1 answer

Not the best answer, because I did not do it myself, but, seeing how it was 3 hours, I will do everything I can.

Annotation Processing Overview

If annotation processing is not disabled with the -proc: none option, the compiler searches for any annotation processors that are available. The search path can be specified using the -processorpath option; if it is not specified, the user uses the class path. Processors hosted by the service provider configuration files named
META-INF / services / javax.annotation.processing.Processor in the search path. Such files should contain the names of any annotation processors that will be used by the line. Alternatively, processors can be specified explicitly using an -processor.

So, you need to create a file called javax.annotation.processing.Processor in the META-INF/services folder, which lists the names of your annotation processors, one per line.

EDIT: So, I believe the code for reading annotations will be similar to ...

  for (Element element : roundEnv.getRootElements()) { State state = element.getAnnotation(State.class); if(state != null) { String stage = state.stage(); System.out.println("The element " + element + " has stage " + stage); } } 

Here you can find a real example annotation processor here .

+5
source

Source: https://habr.com/ru/post/890603/


All Articles