A handy and powerful technique for generating additional source files during compilation.
- Source files can be any type of files (Java files, documentation, resources, and etc).
- It can only be used to generate new files, not to change existing ones.
The annotation is done in multiple rounds. Each round includes:
- Compiler searches for the annotations.
- Compiler chooses annotation processor suited for these annotations.
- Each annotation processor 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 completes when no new files are generated.
Applying annotation processing technique to generate source files includes the following steps:
- Define required @annotations and how it can be used.
- Write custom processors which extends
AbstractProcessor
class. - In each processor
- Filter corresponding annotations.
- Verify the correctness of annotated elements and use
Messager
to show useful messages. - Retrieve all necessary information(i.e: class name, method name, argument type) which are used to generate source files.
- Generate output files (by using
Filer
).
- AutoService: Generates processor metadata file.
- JavaPoet: Generates
.java
source files.