Java – annotation processor – how to get the class it is processing
•
Java
I'm trying to write a custom annotation processor
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); } } }
Solution
You cannot access the class being processed by the annotation processor because the class has not been compiled Instead, Java provides a similar elements API for reflective checking of input sources
Element (found by using roundenv. Getrootelements()) has more information about the class being compiled, not just its name Using elementvisitors, you can find a lot of useful information:
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 class constructors, 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 } } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码