Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotation - Read element value at build-time

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

public @interface State {
    String stage();
}

and I annotate a method in a class, like so:

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

How can I read the value of the @State annotation element 'stage' at build time, in an 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;
    }
}
like image 337
Joeblackdev Avatar asked Jun 15 '11 13:06

Joeblackdev


1 Answers

Not the best answer as I haven't done this myself, but seeing as it's been 3 hours I'll do what I can.

Overview of annotation processing

Unless annotation processing is disabled with the -proc:none option, the compiler searches for any annotation processors that are available. The search path can be specified with the -processorpath option; if it is not given, the user class path is used. Processors are located by means of service provider-configuration files named
META-INF/services/javax.annotation.processing.Processor on the search path. Such files should contain the names of any annotation processors to be used, listed one per line. Alternatively, processors can be specified explicitly, using the -processor option.

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

EDIT: So then I believe the code to read the annotations would be something like...

    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);
        }
    }

A real-world example of an annotation processor can be found here.

like image 128
Pace Avatar answered Sep 20 '22 22:09

Pace