Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I examine the whole source tree with an annotation processor?

I have a lot of handler classes that handle specific message types. To register all these handlers, I need to know which ones exist. Currently, they're all annotated with a specific annotation, and I use a Java 6 annotation processor to get all of them, and make a Register class that holds an instance of each of the annotated types.

This works great if the whole tree is being built at once, but if just one of the annotated classes is being built (when I save the file in Eclipse, for example), the processor only sees that type, and builds an incomplete Register. How can I examine the other types in this scenario?

like image 635
Tavian Barnes Avatar asked May 14 '12 14:05

Tavian Barnes


People also ask

How does annotation processor work?

Annotation Processing APIEach annotation processor, in turn, is called on the corresponding sources. If any files are generated during this process, another round is started with the generated files as its input. This process continues until no new files are generated during the processing stage.

What is annotation processor in gradle?

Annotation processing is a powerful tool for generating code for Android apps. In this tutorial, you'll create one that generates RecyclerView adapters.

What is annotation processor in eclipse?

The JDT-APT project provides plugins that add Java 5 annotation processing support to Eclipse. A Java annotation processor is a compiler plug-in that can gather information about source code as it is being compiled, generate additional Java types or other resource files, and post warnings and errors.


1 Answers

I've solved this well enough for now. What I did is a little hackey, but basically for every annotated class I see, I add its name to a HashSet. Then I use Filer.getResource() to get open a file where I've recorded all the previously-seen annotated classes, and add those to the HashSet too. Then I generate the register class, and write the whole HashSet out to the same resource with Filer.createResource(). This will cause problems if I delete an annotated type, since it will still be recorded in that file, but I can just clean the project or delete that file to solve it.

EDIT: Also, I believe that passing the appropriate "originating elements" to Filer.createSource() should allow Eclipse to track those dependencies properly, but it doesn't. Perhaps that's an Eclipse bug.

like image 145
Tavian Barnes Avatar answered Oct 04 '22 14:10

Tavian Barnes