Annotation Processor - How to get the Class it is processing

user1004413 picture user1004413 · Aug 3, 2013 · Viewed 10.6k times · Source

I am trying to write a custom Anntoation processor. The annotation processor will process each class file at compile time to check annotations, But how am i able to get the class that it is currently processing? I am only able to get the class name in the following codes.

public class AnnotationProcessor extends AbstractProcessor {
  ......
    @Override
     public boolean process(Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv) {

     Set<? extends Element> rootE=roundEnv.getRootElements();
       for(Element e: rootE) {
        if(e.getKind()==ElementKind.CLASS) {
            String className= e.getSimpleName().toString();
            processingEnv.getMessager().printMessage( javax.tools.Diagnostic.Kind.WARNING,className, e); 
        }
     }
}

Answer

John Ericksen picture John Ericksen · Aug 13, 2013

You are unable to access the Class the Annotation Processor is processing because the Class has not been compiled yet. Instead Java offers the analogous Elements api for reflection-style inspection of the input source.

The Element (which you found by using roundEnv.getRootElements()) has much more information about the class being compiled than just its name. A ton of useful information can be found by using the ElementVisitors:

http://docs.oracle.com/javase/6/docs/api/javax/lang/model/element/ElementVisitor.html http://docs.oracle.com/javase/6/docs/api/javax/lang/model/util/ElementKindVisitor6.html

Including the classes constructor, methods, fields, etc.

Here's how to use it:

public class AnnotationProcessor extends AbstractProcessor {
......
    @Override
     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

         Set<? extends Element> rootE=roundEnv.getRootElements();
         for(Element e: rootE) {
             for(Element subElement : e.getEnclosedElements()){
                 subElement.accept(new ExampleVisitor(), null); // implement ExampleVisitor
             }
        }
    }
}