SlideShare a Scribd company logo
Daggerate
your code
ANNOTATION PROCESSING
Bartosz Kosarzycki
@bkosarzycki
● Annotations in Java
● Libraries useful in annotation processing
● Basic annotation processor
● Round environment
● Idea
● How to write your annotation processor tutorial
● Debug annotation processing
Agenda
Annotations in Java:
- since Java 1.5
- store meta-information
#pragma in c / c# attributes
- JSR-269 - since 1.6
Pluggable Annotation
Processing API for apt tool,
built-into javac
- custom annotations
Annotations in Java:
- Annotation @Retention
how long annotations
are kept
SOURCE,
CLASS,
RUNTIME
Annotations in Java:
SOURCE
discarded by the compiler
CLASS
kept int the class file, not loaded
by the JVM at runtime
RUNTIME
loaded by the JVM at runtime
Libraries
● Google AutoService link
register implementations of well-known types using META-INF
metadata
● Square JavaPoet link
generate Java source code
● Google Compile-Testing link
test javac compilation process
Basic annotation processor
@AutoService(Processor.class)
public class YourProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> set,
RoundEnvironment roundEnvironment) {
return false;
}
}
@AutoService(Processor.class)
public class YourProcessor extends AbstractProcessor {
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton( Injection.class.getCanonicalName() );
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
}
}
Implement these methods as well
Basic annotation processor
Basic annotation processor
@AutoService(Processor.class)
public class YourProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> set,
RoundEnvironment roundEnvironment) {
return false;
}
}
Processing rounds
javac
apt
Processing rounds
javac
apt
rounds
until there is no change in sources
source
source
set
the annotation types requested to be processed
roundEnvironment
environment information about the current and prior round
return:
whether or not the set of annotations are claimed by this processor
@Override
public boolean process(Set<? extends TypeElement> set,
RoundEnvironment roundEnvironment) {
return false;
}
*** always return false
IDEA
What was the
RoboJuice + Dagger 2
RoboJuice
DYNAMIC
final RoboInjector injector = RoboGuice.getInjector(context);
annotation injector.injectMembers(this);
or
foo = injector.getInstance(Foo.class);
Dagger 2
Compile time
No runtime overhead of scanning the classpath
Idea
Modules can be imported dynamically
Modules expose Dagger 2 injectable objects
Module 1
Module 2
App
Developer imports modules
Injector constains MembersInjector &
Providers maps
Injector.get() & Injector.inject() methods
work dynamically
REUSABLE ANDROID SDK
ENVIRONMENT
Android
developer
dependencies {
compile 'com.you.app:module.one:6.6.6'
}
@Injection(modules = { ModuleOne.class })
public class MainApplication extends Application {
}
Foo foo = Injector.getInstance(Foo.class);
How to write
an annotation
processor?
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton( Injection.class.getCanonicalName() );
}
How-to
Set annotations supported by your processor:
Set supported java-source version:
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest(); // SourceVersion.RELEASE_8;
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
filer = processingEnv.getFiler();
}
How-to
Get “Filer” to write source code:
Files are written to:
build/generated/source/apt/debug
build/generated/source/apt/release
Hint
Class
Object
TypeMirror
- Use description of types instead of types
- Classes are NOT available yet - they are STILL
COMPILED
Class<?> clazz = Class.forName("your.app.package.YourType");
ClassNotFoundException
@Example
public class Foo {
private int a;
private Other other;
public Foo () {
}
public void setA
( int newA
) { }
}
Type descriptions
TypeElement
VariableElement
ExecutableElement
ExecutableElement
TypeElement
Analyse source
Gather information
Write new source files
Modify current source files
Use gathered information
AnnotationProcessor
for (Element typeElement :
roundEnvironment.getElementsAnnotatedWith(Injection.class)) {
String name = typeElement.getSimpleName().toString();
}
Get all elements with a specific annotation:
typeElement.getEnclosedElements();
typeElement.getEnclosingElement();
Moving up & down the type hiararchy:
AnnotationProcessor
for (AnnotationMirror annotationMirror : ((DeclaredType)module).asElement().getAnnotationMirrors()) {
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
annotationMirror.getElementValues().entrySet()) {
// use the entry with AnnotationValueVisitor
}
}
Get annotations from TypeMirror:
final String[] annotationParam = new String[1];
final AnnotationValueVisitor valueVisitor = new AnnotationValueVisitor();
valueVisitor.setFunction(new Function<TypeMirror, Void>() {
@Nullable @Override public Void apply(@Nullable TypeMirror param) {
TypeMirror moduleClass = param; //assembles modules list
return null;
}
});
annotationParam[0] = entry.getKey().getSimpleName().toString();
entry.getValue().accept(valueVisitor, null);
@Annotation(param = { Sample.class })
Class<?>[] param()
Sample.class
Square’s
JavaPoet
Thank you
@JakeWharton ;)
Square’s JavaPoet
Thank you
@JakeWharton ;)
● works with TypeMirrors
out of the box
● adds imports automatically
● removes duplicate imports
● supports static imports
● code & control flow
for / if etc.
● built-in support for Filer
JavaPoet
MethodSpec.Builder constructorMethod =
MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC)
.addCode("this(" +
"$1T" +
".builder().build()); n",
typeMirror);
Create methods using JavaPoet:
TypeSpec typeSpec = TypeSpec.classBuilder(outputClassName)
.addModifiers(Modifier.PUBLIC)
.superclass(...)
.addJavadoc("annotation processor ...")
.addField(componentElem, "innerField", Modifier.PRIVATE, Modifier.FINAL)
.addMethod(constructorMethod.build())
.build();
Create types using JavaPoet:
* imports are added automatically here
JavaPoet
ClassName.get("your.package.name”, "DaggerInjector")
Create custom unreachable types (ClassName) :
* imports are added automatically as well
Filer
JavaFile.builder("your.package.name", typeSpec).build().writeTo(filer);
Write source code using JavaPoet & Filer:
filer.createSourceFile("public class A() {}", null);
Write source code Filer:
Debugging
Debugging
● Annotation processing cannot
be debugged directly
● Compile project with gradle
in debug mode
● Attach to the compile process
from IDE
● [OPTIONAL] configure scripts
to launch debug from IDE
Detailed tutorial here
Links
- Angelika Langer, Annotation Processing link
- Hannes Dorfmann, Annotation Processing 101 link link
- JavaDocs: Element, TypeElement, ExecutableElement
Thank you!
QUESTIONS
Bartosz Kosarzycki
@bkosarzycki

More Related Content

What's hot (19)

PDF
CDI: How do I ?
Antonio Goncalves
 
PDF
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
PDF
Architectures in the compose world
Fabio Collini
 
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
PDF
Using hilt in a modularized project
Fabio Collini
 
PDF
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
PDF
Kotlin Delegates in practice - Kotlin community conf
Fabio Collini
 
PDF
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
GuardSquare
 
PDF
Dependency Injection with CDI in 15 minutes
Antonio Goncalves
 
PDF
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Fabio Collini
 
PDF
Kotlin hands on - MorningTech ekito 2017
Arnaud Giuliani
 
PDF
A friend in need - A JS indeed
Yonatan Levin
 
PDF
Why Spring <3 Kotlin
VMware Tanzu
 
PPTX
Introduction to CDI and DI in Java EE 6
Ray Ploski
 
ODP
To inject or not to inject: CDI is the question
Antonio Goncalves
 
PDF
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Badoo Development
 
PPTX
GDG Kuwait - Modern android development
GDGKuwaitGoogleDevel
 
PDF
Kotlin: Why Do You Care?
intelliyole
 
PPTX
Workshop 1: Good practices in JavaScript
Visual Engineering
 
CDI: How do I ?
Antonio Goncalves
 
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Architectures in the compose world
Fabio Collini
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
Using hilt in a modularized project
Fabio Collini
 
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
Kotlin Delegates in practice - Kotlin community conf
Fabio Collini
 
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
GuardSquare
 
Dependency Injection with CDI in 15 minutes
Antonio Goncalves
 
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Fabio Collini
 
Kotlin hands on - MorningTech ekito 2017
Arnaud Giuliani
 
A friend in need - A JS indeed
Yonatan Levin
 
Why Spring <3 Kotlin
VMware Tanzu
 
Introduction to CDI and DI in Java EE 6
Ray Ploski
 
To inject or not to inject: CDI is the question
Antonio Goncalves
 
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Badoo Development
 
GDG Kuwait - Modern android development
GDGKuwaitGoogleDevel
 
Kotlin: Why Do You Care?
intelliyole
 
Workshop 1: Good practices in JavaScript
Visual Engineering
 

Viewers also liked (18)

PDF
Android antipatterns
Bartosz Kosarzycki
 
PPTX
Weld Strata talk
Deepak Narayanan
 
PDF
Introduction to Flutter - truly crossplatform, amazingly fast
Bartosz Kosarzycki
 
PDF
Reark : a Reference Architecture for Android using RxJava
Futurice
 
PDF
Gitlab flow
viniciusban
 
PPTX
Re-implementing Thrift using MDE
Sina Madani
 
PDF
Thesis: Slicing of Java Programs using the Soot Framework (2006)
Arvind Devaraj
 
PDF
Introduction to Golang final
Paul Chao
 
PDF
Gitlab flow solo
viniciusban
 
PPTX
Singleton class in Java
Rahul Sharma
 
PDF
Git-flow workflow and pull-requests
Bartosz Kosarzycki
 
PDF
BUD17-302: LLVM Internals #2
Linaro
 
PPTX
Embedded Linux/ Debian with ARM64 Platform
SZ Lin
 
PDF
Linux-wpan: IEEE 802.15.4 and 6LoWPAN in the Linux Kernel - BUD17-120
Linaro
 
PPT
Database concurrency control &amp; recovery (1)
Rashid Khan
 
PDF
BUD17-218: Scheduler Load tracking update and improvement
Linaro
 
PPTX
Distributed system &amp; its characteristic
Akash Rai
 
PPTX
Mobile os (msquare)
Mahesh Makwana
 
Android antipatterns
Bartosz Kosarzycki
 
Weld Strata talk
Deepak Narayanan
 
Introduction to Flutter - truly crossplatform, amazingly fast
Bartosz Kosarzycki
 
Reark : a Reference Architecture for Android using RxJava
Futurice
 
Gitlab flow
viniciusban
 
Re-implementing Thrift using MDE
Sina Madani
 
Thesis: Slicing of Java Programs using the Soot Framework (2006)
Arvind Devaraj
 
Introduction to Golang final
Paul Chao
 
Gitlab flow solo
viniciusban
 
Singleton class in Java
Rahul Sharma
 
Git-flow workflow and pull-requests
Bartosz Kosarzycki
 
BUD17-302: LLVM Internals #2
Linaro
 
Embedded Linux/ Debian with ARM64 Platform
SZ Lin
 
Linux-wpan: IEEE 802.15.4 and 6LoWPAN in the Linux Kernel - BUD17-120
Linaro
 
Database concurrency control &amp; recovery (1)
Rashid Khan
 
BUD17-218: Scheduler Load tracking update and improvement
Linaro
 
Distributed system &amp; its characteristic
Akash Rai
 
Mobile os (msquare)
Mahesh Makwana
 
Ad

Similar to Daggerate your code - Write your own annotation processor (20)

PDF
Sharper Better Faster Dagger ‡ - Droidcon SF
Pierre-Yves Ricau
 
PPTX
Annotation processing
Florent Champigny
 
PDF
Annotation Processing
Jintin Lin
 
PDF
Devoxx 2012 (v2)
Jerome Dochez
 
PDF
Annotation Processing in Android
emanuelez
 
PPTX
Module design pattern i.e. express js
Ahmed Assaf
 
PPTX
Angular 2 Migration - JHipster Meetup 6
William Marques
 
PDF
Effective JavaFX architecture with FxObjects
Srikanth Shenoy
 
PDF
What's Coming in Spring 3.0
Matt Raible
 
PDF
TypeScript for Java Developers
Yakov Fain
 
KEY
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Howard Lewis Ship
 
PDF
Objective-C Runtime overview
Fantageek
 
PDF
Overview of Android Infrastructure
Alexey Buzdin
 
PDF
Overview of Android Infrastructure
C.T.Co
 
PDF
Workshop 26: React Native - The Native Side
Visual Engineering
 
PDF
Architecting your GWT applications with GWT-Platform - Lesson 02
rhemsolutions
 
PDF
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Sigma Software
 
PPT
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
PDF
Struts2 notes
Rajiv Gupta
 
PDF
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Pierre-Yves Ricau
 
Annotation processing
Florent Champigny
 
Annotation Processing
Jintin Lin
 
Devoxx 2012 (v2)
Jerome Dochez
 
Annotation Processing in Android
emanuelez
 
Module design pattern i.e. express js
Ahmed Assaf
 
Angular 2 Migration - JHipster Meetup 6
William Marques
 
Effective JavaFX architecture with FxObjects
Srikanth Shenoy
 
What's Coming in Spring 3.0
Matt Raible
 
TypeScript for Java Developers
Yakov Fain
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Howard Lewis Ship
 
Objective-C Runtime overview
Fantageek
 
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
C.T.Co
 
Workshop 26: React Native - The Native Side
Visual Engineering
 
Architecting your GWT applications with GWT-Platform - Lesson 02
rhemsolutions
 
Android App Architecture with modern libs in practice. Our way in R.I.D., Ser...
Sigma Software
 
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
Struts2 notes
Rajiv Gupta
 
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Ad

More from Bartosz Kosarzycki (12)

PDF
Droidcon Summary 2021
Bartosz Kosarzycki
 
PDF
Droidcon Online 2020 quick summary
Bartosz Kosarzycki
 
PDF
Provider vs BLoC vs Redux
Bartosz Kosarzycki
 
PDF
Animations in Flutter
Bartosz Kosarzycki
 
PDF
Flutter overview - advantages & disadvantages for business
Bartosz Kosarzycki
 
PDF
Flutter CI & Device Farms for Flutter
Bartosz Kosarzycki
 
PDF
Drone racing - beginner's guide
Bartosz Kosarzycki
 
PDF
Optimize apps for Chromebooks - Meet.Intive Oct, 2018
Bartosz Kosarzycki
 
PDF
Android - Gradle build optimisation 3d83f31339d239abcc55f869e5f30348?s=47
Bartosz Kosarzycki
 
PDF
DroidCon Berlin 2018 summary
Bartosz Kosarzycki
 
PDF
SCALA - Functional domain
Bartosz Kosarzycki
 
PDF
Android things introduction - Development for IoT
Bartosz Kosarzycki
 
Droidcon Summary 2021
Bartosz Kosarzycki
 
Droidcon Online 2020 quick summary
Bartosz Kosarzycki
 
Provider vs BLoC vs Redux
Bartosz Kosarzycki
 
Animations in Flutter
Bartosz Kosarzycki
 
Flutter overview - advantages & disadvantages for business
Bartosz Kosarzycki
 
Flutter CI & Device Farms for Flutter
Bartosz Kosarzycki
 
Drone racing - beginner's guide
Bartosz Kosarzycki
 
Optimize apps for Chromebooks - Meet.Intive Oct, 2018
Bartosz Kosarzycki
 
Android - Gradle build optimisation 3d83f31339d239abcc55f869e5f30348?s=47
Bartosz Kosarzycki
 
DroidCon Berlin 2018 summary
Bartosz Kosarzycki
 
SCALA - Functional domain
Bartosz Kosarzycki
 
Android things introduction - Development for IoT
Bartosz Kosarzycki
 

Recently uploaded (20)

PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Tally software_Introduction_Presentation
AditiBansal54083
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 

Daggerate your code - Write your own annotation processor