How to write your own annotation processor in Android Studio. Compile time and runtime annotations will be compared to reflection. To conclude, butterknife library will be presented as an example of using compile time annotation processing.
3. Let’s look at our options
Generics Reflection Annotations
Speed Fast Slow
Fast (if using
compile time)
Ease of use Easy Medium Advanced
“Freedom" - generic types
- modify everything
at run-time
- generate code
during compile
4. • use generics for type agnostic structures when
possible (e.g. lists) - it’s easy and fast
• when that isn’t enough, use annotation processing -
generate code that is boring to write
• generated code isn’t “visible” - use reflection to access
it at run time from the code that you write
Approach
5. Let’s get our hands dirty
• actually only the keyboard gets dirty over time
• prerequisites:
- Android Studio (tested on version 0.4.0)
- enable annotation processing
(Open preference and navigate to Compiler → Annotation Processors.
Check "Enable annotation processing”)
- apt plugin https://bitbucket.org/hvisser/android-apt
• what is an annotation processor made of?
- definition of annotations using @interface
- a class that extends AbstractProcessor
- entry containing processor name in
META-INF/services/javax.annotation.processing.Processor
6. Project structure
• API project
- annotation definitions
- other non-generated code
• Compiler project
- annotation processor implementation
- annotation definitions (from API project) on
classpath
• Application project
- android application project
- references to API and Compiler projects
8. Compiler project
• standard java library project
- this is required in order to see APT classes
• API project sources must be in classpath (build.gradle):
9. Compiler project
• AbstractProcessor implementation
- override process(…) method
- return true if processing was successfull
- add following annotations to processor class:
@SupportedAnnotationTypes(“your.package.AnnotationName”)
@SupportedSourceVersion(SourceVersion.RELEASE_7)
• create file:
src/main/resources/META-INF/services/javax.annotation.processing.Processor
• add fully qualified class name of your processor class to the
file (e.g. co.infinum.annotations.processor.TestProcessor)