SlideShare a Scribd company logo
ANNOTATION PROCESSING
IN ANDROIDEmanuele Zattin - Realm
@emanuelez
19-2-2016 - DroidKaigi
DroidKaigi
WHAT IS A JAVA
ANNOTATION?
LET'S START WITH THE OFFICIAL
DEFINITION
Annotations, a form of metadata, provide data about a
program that is not part of the program itself.
Annotations have no direct effect on the operation of the
code they annotate.
— Oracle
WHAT CAN ANNOTATIONS DO?
1. Provide information for the compiler
2. Allow runtime processing
3. Allow compile-time processing
HOW TO DEFINE AN ANNOTATION
The simplest annotation can be defined as:
public @interface MyAnnotation {}
and it can be used like this:
@MyAnnotation
public class MyClass {}
ANNOTATIONS CAN ACCEPT
ARGUMENTS
public @interface MyAnnotation {
String arg1();
int arg2 default 1;
String[] arg3;
}
Which can be used like this:
@MyAnnotation (
arg1 = "value1", // It's a comma, not a semicolon
arg3 = { "value2", "value3" } // Arrays use curly brackets
)
public class MyClass {}
ANNOTATIONS CAN BE ANNOTATED
The most important is @Retention which value can
be:
▸ RetentionPolicy.SOURCE
▸ RetentionPolicy.CLASS
▸ RetentionPolicy.RUNTIME
ANNOTATIONS CAN BE ANNOTATED
PART 2
The other important annotation is @Target which
value:
ElementType.ANNOTATION_TYPE
ElementType.CONSTRUCTOR
ElementType.FIELD
ElementType.LOCAL_VARIABLE
ElementType.METHOD
ANNOTATIONS CAN BE ANNOTATED
PART 3
Other useful annotations:
▸ @Documented
▸ @Inherited
▸ @Repeatable
AN EXAMPLE ANNOTATION
@Retention(RetentionPolicy.CLASS) // Available at compile-time
@Target(ElementType.TYPE) // Can only be applied to classes
@interface MyAnnotation {
String arg1();
int arg2 default 1;
String[] arg3;
}
WHAT IS AN
ANNOTATION
PROCESSOR?
Annotation Processing is a technique that provides
a hook into the Java compile process.
It allows to produce compiler errors and warnings
and to generate source code and byte code.
JSR 269
HOW DOES IT WORK?
Here's a high-level example:
1. Normal compilation
2. First round of annotation processing
3. Second round of annotation processing
4. ...
IMPLEMENTING A PROCESSOR
public abstract class AbstractProcessor implements Processor {
// more methods here!
void init(
ProcessingEnvironment processingEnv
);
abstract boolean process(
Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv
);
}
THE PROCESSING ENVIRONMENT
It provides the tools to write new files and access utility
classes.
Here are the most useful methods:
// Use Filer to write new files
Filer getFiler();
// Use Elements to manage fields, methods and classes
Elements getElementUtils();
// Use Types to deal with classes, converting Type to Element, ...
Types getTypeUtils();
THE ROUND ENVIRONMENT
It provides tools to deal with the specific round.
The most useful methods are:
// Get the elements annotated with a given annotation
Set<? extends Element> getElementsAnnotatedWith(Class<? extends Annotation> a);
Set<? extends Element> getElementsAnnotatedWith(TypeElement a);
THE MOST USELESS ANNOTATION
public AnnoyingProcessor extends AbstractProcessor {
boolean process( Set<> annotations, RoundEnvironment env) {
Messager m = processingEnv.getMessager();
for (TypeElement te : annotations) {
for (Element e : env.getElementsAnnotatedWith(te)) {
m.printMessage(Diagnostic.Kind.NOTE, "Processing " + e.toString());
}
}
return true;
}
}
REGISTERING YOUR PROCESSOR
1. Package your processor in a Jar file
2. The Jar file must contain a file called
javax.annotation.processing.Proce
ssor
located in META-INF/services
3. This file must contain the fully
qualified name of your processor
GENERATING JAVA CODE IN YOUR AP
Enter JavaPoet
MethodSpec main = MethodSpec.methodBuilder("main")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(void.class)
.addParameter(String[].class, "args")
.addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(main)
.build();
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
.build();
javaFile.writeTo(processingEnv.getFiler());
TESTING
Testing annotations processors is hard because the
execution happens at compile time
SOME MUCH NEEDED HELP!
Google's compile-testing library
EXAMPLE 1
assert_() // it uses the Truth testing library
.about(javaSource())
.that(
JavaFileObjects.forSourceString(
"HelloWorld", "final class HelloWorld {}"
)
).compilesWithoutError();
EXAMPLE 2
assert_().about(javaSource())
.that(JavaFileObjects.forResource("HelloWorld.java"))
.processedWith(new MyAnnotationProcessor())
.compilesWithoutError()
.and()
.generatesSources(
JavaFileObjects.forResource("GeneratedHelloWorld.java"));
HOW ABOUT
ANNOTATION
PROCESSING IN
ANDROID?
PROBLEM 1
The Android framework does not include
javax.annotation.processing
SOLUTION
Setup your AP to be a Java module
and to inform your users to use
the Gradle android-apt plugin by Hugo Visser
PROBLEM 2
Both your library and your AP might depend on the
annotations
SOLUTION
Setup your annotations to be another Java module
on which both the library and the AP depend on
PROBLEM 3
Now the Javadoc of your library does not include the
annotations
SOLUTION
android.libraryVariants.all { variant ->
task("javadoc${variant.name.capitalize()}", type: Javadoc) {
description "Generates Javadoc for $variant.name."
group 'Docs'
source = variant.javaCompile.source
source "../annotations/src/main/java" // <-- THIS!
ext.androidJar = files(project.android.getBootClasspath())
classpath = files(variant.javaCompile.classpath.files)
+ ext.androidJar
exclude '**/BuildConfig.java'
exclude '**/R.java'
}
}
ANDROID LIBRARIES THAT USE AP
▸ ButterKnife
▸ Dagger
▸ Parceler
▸ Realm
Thank you!
Questions?

More Related Content

What's hot

#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
Nattapong Tonprasert
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
Iram Ramrajkar
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
Carol McDonald
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
Danairat Thanabodithammachari
 
7.Spring DI_2
7.Spring DI_27.Spring DI_2
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
Raji Ghawi
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
NIO and NIO2
NIO and NIO2NIO and NIO2
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
Fahad Shaikh
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
Ganesh Samarthyam
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
Ganesh Samarthyam
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
Jorge Hidalgo
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation Processing
Jintin Lin
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
Abdelmonaim Remani
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
Rafael Winterhalter
 

What's hot (20)

#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
 
Project Coin
Project CoinProject Coin
Project Coin
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
7.Spring DI_2
7.Spring DI_27.Spring DI_2
7.Spring DI_2
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation Processing
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
 

Viewers also liked

Fearless Internationalization and Localization Across the Nations
Fearless Internationalization and Localization Across the NationsFearless Internationalization and Localization Across the Nations
Fearless Internationalization and Localization Across the Nations
Siena Aguayo
 
ライブコーディング・Androidのライブラリを作ってみよう
ライブコーディング・Androidのライブラリを作ってみようライブコーディング・Androidのライブラリを作ってみよう
ライブコーディング・Androidのライブラリを作ってみよう
Masataka Kono
 
5 年続く 「はてなブックマーク」 アプリを継続開発する技術
5 年続く 「はてなブックマーク」 アプリを継続開発する技術5 年続く 「はてなブックマーク」 アプリを継続開発する技術
5 年続く 「はてなブックマーク」 アプリを継続開発する技術
Yu Nobuoka
 
Customizing Theme and Style for Material Design : Droid Kaigi 2016
Customizing Theme and Style for Material Design : Droid Kaigi 2016Customizing Theme and Style for Material Design : Droid Kaigi 2016
Customizing Theme and Style for Material Design : Droid Kaigi 2016
Yuki Anzai
 
ChromeとAndroidの過去・現在・未来
ChromeとAndroidの過去・現在・未来ChromeとAndroidの過去・現在・未来
ChromeとAndroidの過去・現在・未来
Shinobu Okano
 
Android,Brillo,ChromeOS
Android,Brillo,ChromeOSAndroid,Brillo,ChromeOS
Android,Brillo,ChromeOS
l_b__
 
明日から使えるRxjava頻出パターン (Droid kaigi 2016)
明日から使えるRxjava頻出パターン (Droid kaigi 2016)明日から使えるRxjava頻出パターン (Droid kaigi 2016)
明日から使えるRxjava頻出パターン (Droid kaigi 2016)
Kazuki Yoshida
 
Master of Canvas
Master of CanvasMaster of Canvas
Master of Canvas
Mima Yuki
 
怖くないGradle設定とBazel
怖くないGradle設定とBazel怖くないGradle設定とBazel
怖くないGradle設定とBazel
shimada tatsuya
 
AndroidLint #DroidKaigi
AndroidLint #DroidKaigiAndroidLint #DroidKaigi
AndroidLint #DroidKaigi
Yukiya Nakagawa
 
Androidのセキュア開発について考えてみた(明日、敗訴しないためのセキュアコーディング.ver2)
Androidのセキュア開発について考えてみた(明日、敗訴しないためのセキュアコーディング.ver2)Androidのセキュア開発について考えてみた(明日、敗訴しないためのセキュアコーディング.ver2)
Androidのセキュア開発について考えてみた(明日、敗訴しないためのセキュアコーディング.ver2)
Kengo Suzuki
 
DroidKaigi2016 windows環境での効率的なアプリ開発手法
DroidKaigi2016 windows環境での効率的なアプリ開発手法DroidKaigi2016 windows環境での効率的なアプリ開発手法
DroidKaigi2016 windows環境での効率的なアプリ開発手法
tkawashita
 
用途に合わせたアニメーションの実装方法
用途に合わせたアニメーションの実装方法用途に合わせたアニメーションの実装方法
用途に合わせたアニメーションの実装方法
Takao Sumitomo
 
Go MobileでAndroidアプリ開発
Go MobileでAndroidアプリ開発Go MobileでAndroidアプリ開発
Go MobileでAndroidアプリ開発
Takuya Ueda
 
パーミッションモデルの過渡期への対応
パーミッションモデルの過渡期への対応パーミッションモデルの過渡期への対応
パーミッションモデルの過渡期への対応
ak_shio_555
 
Android Dev Tools Knowledge
Android Dev Tools KnowledgeAndroid Dev Tools Knowledge
Android Dev Tools Knowledge
Shinobu Okano
 
最速でリリースするためのAndroidアプリデザイン
最速でリリースするためのAndroidアプリデザイン最速でリリースするためのAndroidアプリデザイン
最速でリリースするためのAndroidアプリデザイン
Naoki Aoyama
 
Android lint-srp-practice
Android lint-srp-practiceAndroid lint-srp-practice
Android lint-srp-practice
cch-robo
 
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
Masataka Kono
 
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigiReact Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
Yukiya Nakagawa
 

Viewers also liked (20)

Fearless Internationalization and Localization Across the Nations
Fearless Internationalization and Localization Across the NationsFearless Internationalization and Localization Across the Nations
Fearless Internationalization and Localization Across the Nations
 
ライブコーディング・Androidのライブラリを作ってみよう
ライブコーディング・Androidのライブラリを作ってみようライブコーディング・Androidのライブラリを作ってみよう
ライブコーディング・Androidのライブラリを作ってみよう
 
5 年続く 「はてなブックマーク」 アプリを継続開発する技術
5 年続く 「はてなブックマーク」 アプリを継続開発する技術5 年続く 「はてなブックマーク」 アプリを継続開発する技術
5 年続く 「はてなブックマーク」 アプリを継続開発する技術
 
Customizing Theme and Style for Material Design : Droid Kaigi 2016
Customizing Theme and Style for Material Design : Droid Kaigi 2016Customizing Theme and Style for Material Design : Droid Kaigi 2016
Customizing Theme and Style for Material Design : Droid Kaigi 2016
 
ChromeとAndroidの過去・現在・未来
ChromeとAndroidの過去・現在・未来ChromeとAndroidの過去・現在・未来
ChromeとAndroidの過去・現在・未来
 
Android,Brillo,ChromeOS
Android,Brillo,ChromeOSAndroid,Brillo,ChromeOS
Android,Brillo,ChromeOS
 
明日から使えるRxjava頻出パターン (Droid kaigi 2016)
明日から使えるRxjava頻出パターン (Droid kaigi 2016)明日から使えるRxjava頻出パターン (Droid kaigi 2016)
明日から使えるRxjava頻出パターン (Droid kaigi 2016)
 
Master of Canvas
Master of CanvasMaster of Canvas
Master of Canvas
 
怖くないGradle設定とBazel
怖くないGradle設定とBazel怖くないGradle設定とBazel
怖くないGradle設定とBazel
 
AndroidLint #DroidKaigi
AndroidLint #DroidKaigiAndroidLint #DroidKaigi
AndroidLint #DroidKaigi
 
Androidのセキュア開発について考えてみた(明日、敗訴しないためのセキュアコーディング.ver2)
Androidのセキュア開発について考えてみた(明日、敗訴しないためのセキュアコーディング.ver2)Androidのセキュア開発について考えてみた(明日、敗訴しないためのセキュアコーディング.ver2)
Androidのセキュア開発について考えてみた(明日、敗訴しないためのセキュアコーディング.ver2)
 
DroidKaigi2016 windows環境での効率的なアプリ開発手法
DroidKaigi2016 windows環境での効率的なアプリ開発手法DroidKaigi2016 windows環境での効率的なアプリ開発手法
DroidKaigi2016 windows環境での効率的なアプリ開発手法
 
用途に合わせたアニメーションの実装方法
用途に合わせたアニメーションの実装方法用途に合わせたアニメーションの実装方法
用途に合わせたアニメーションの実装方法
 
Go MobileでAndroidアプリ開発
Go MobileでAndroidアプリ開発Go MobileでAndroidアプリ開発
Go MobileでAndroidアプリ開発
 
パーミッションモデルの過渡期への対応
パーミッションモデルの過渡期への対応パーミッションモデルの過渡期への対応
パーミッションモデルの過渡期への対応
 
Android Dev Tools Knowledge
Android Dev Tools KnowledgeAndroid Dev Tools Knowledge
Android Dev Tools Knowledge
 
最速でリリースするためのAndroidアプリデザイン
最速でリリースするためのAndroidアプリデザイン最速でリリースするためのAndroidアプリデザイン
最速でリリースするためのAndroidアプリデザイン
 
Android lint-srp-practice
Android lint-srp-practiceAndroid lint-srp-practice
Android lint-srp-practice
 
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
 
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigiReact Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
 

Similar to Annotation Processing in Android

Annotation processing
Annotation processingAnnotation processing
Annotation processing
Florent Champigny
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
Saifur Rahman
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Context and Dependency Injection 2.0
Context and Dependency Injection 2.0
Brian S. Paskin
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
divaskrgupta007
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
Introduction
IntroductionIntroduction
Introduction
richsoden
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Code Documentation. That ugly thing...
Code Documentation. That ugly thing...Code Documentation. That ugly thing...
Code Documentation. That ugly thing...
Christos Manios
 
FileWrite.javaFileWrite.java  To change this license header.docx
FileWrite.javaFileWrite.java  To change this license header.docxFileWrite.javaFileWrite.java  To change this license header.docx
FileWrite.javaFileWrite.java  To change this license header.docx
ssuser454af01
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
Bartosz Kosarzycki
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
Serhii Kartashov
 
Spring boot
Spring bootSpring boot
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
Final Project Presentation
Final Project PresentationFinal Project Presentation
Final Project Presentation
zroserie
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
SMIJava
 

Similar to Annotation Processing in Android (20)

Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Context and Dependency Injection 2.0
Context and Dependency Injection 2.0
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Introduction
IntroductionIntroduction
Introduction
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Code Documentation. That ugly thing...
Code Documentation. That ugly thing...Code Documentation. That ugly thing...
Code Documentation. That ugly thing...
 
FileWrite.javaFileWrite.java  To change this license header.docx
FileWrite.javaFileWrite.java  To change this license header.docxFileWrite.javaFileWrite.java  To change this license header.docx
FileWrite.javaFileWrite.java  To change this license header.docx
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Spring boot
Spring bootSpring boot
Spring boot
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
01slide
01slide01slide
01slide
 
01slide
01slide01slide
01slide
 
Final Project Presentation
Final Project PresentationFinal Project Presentation
Final Project Presentation
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 

Recently uploaded

TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 

Recently uploaded (20)

TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 

Annotation Processing in Android

  • 1. ANNOTATION PROCESSING IN ANDROIDEmanuele Zattin - Realm @emanuelez 19-2-2016 - DroidKaigi
  • 3. WHAT IS A JAVA ANNOTATION?
  • 4. LET'S START WITH THE OFFICIAL DEFINITION Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate. — Oracle
  • 5. WHAT CAN ANNOTATIONS DO? 1. Provide information for the compiler 2. Allow runtime processing 3. Allow compile-time processing
  • 6. HOW TO DEFINE AN ANNOTATION The simplest annotation can be defined as: public @interface MyAnnotation {} and it can be used like this: @MyAnnotation public class MyClass {}
  • 7. ANNOTATIONS CAN ACCEPT ARGUMENTS public @interface MyAnnotation { String arg1(); int arg2 default 1; String[] arg3; } Which can be used like this: @MyAnnotation ( arg1 = "value1", // It's a comma, not a semicolon arg3 = { "value2", "value3" } // Arrays use curly brackets ) public class MyClass {}
  • 8. ANNOTATIONS CAN BE ANNOTATED The most important is @Retention which value can be: ▸ RetentionPolicy.SOURCE ▸ RetentionPolicy.CLASS ▸ RetentionPolicy.RUNTIME
  • 9. ANNOTATIONS CAN BE ANNOTATED PART 2 The other important annotation is @Target which value: ElementType.ANNOTATION_TYPE ElementType.CONSTRUCTOR ElementType.FIELD ElementType.LOCAL_VARIABLE ElementType.METHOD
  • 10. ANNOTATIONS CAN BE ANNOTATED PART 3 Other useful annotations: ▸ @Documented ▸ @Inherited ▸ @Repeatable
  • 11. AN EXAMPLE ANNOTATION @Retention(RetentionPolicy.CLASS) // Available at compile-time @Target(ElementType.TYPE) // Can only be applied to classes @interface MyAnnotation { String arg1(); int arg2 default 1; String[] arg3; }
  • 13. Annotation Processing is a technique that provides a hook into the Java compile process. It allows to produce compiler errors and warnings and to generate source code and byte code.
  • 15. HOW DOES IT WORK? Here's a high-level example: 1. Normal compilation 2. First round of annotation processing 3. Second round of annotation processing 4. ...
  • 16. IMPLEMENTING A PROCESSOR public abstract class AbstractProcessor implements Processor { // more methods here! void init( ProcessingEnvironment processingEnv ); abstract boolean process( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv ); }
  • 17. THE PROCESSING ENVIRONMENT It provides the tools to write new files and access utility classes. Here are the most useful methods: // Use Filer to write new files Filer getFiler(); // Use Elements to manage fields, methods and classes Elements getElementUtils(); // Use Types to deal with classes, converting Type to Element, ... Types getTypeUtils();
  • 18. THE ROUND ENVIRONMENT It provides tools to deal with the specific round. The most useful methods are: // Get the elements annotated with a given annotation Set<? extends Element> getElementsAnnotatedWith(Class<? extends Annotation> a); Set<? extends Element> getElementsAnnotatedWith(TypeElement a);
  • 19. THE MOST USELESS ANNOTATION public AnnoyingProcessor extends AbstractProcessor { boolean process( Set<> annotations, RoundEnvironment env) { Messager m = processingEnv.getMessager(); for (TypeElement te : annotations) { for (Element e : env.getElementsAnnotatedWith(te)) { m.printMessage(Diagnostic.Kind.NOTE, "Processing " + e.toString()); } } return true; } }
  • 20. REGISTERING YOUR PROCESSOR 1. Package your processor in a Jar file 2. The Jar file must contain a file called javax.annotation.processing.Proce ssor located in META-INF/services 3. This file must contain the fully qualified name of your processor
  • 21. GENERATING JAVA CODE IN YOUR AP Enter JavaPoet
  • 22. MethodSpec main = MethodSpec.methodBuilder("main") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(void.class) .addParameter(String[].class, "args") .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!") .build(); TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(main) .build(); JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld) .build(); javaFile.writeTo(processingEnv.getFiler());
  • 23. TESTING Testing annotations processors is hard because the execution happens at compile time
  • 24. SOME MUCH NEEDED HELP! Google's compile-testing library
  • 25. EXAMPLE 1 assert_() // it uses the Truth testing library .about(javaSource()) .that( JavaFileObjects.forSourceString( "HelloWorld", "final class HelloWorld {}" ) ).compilesWithoutError();
  • 28. PROBLEM 1 The Android framework does not include javax.annotation.processing
  • 29. SOLUTION Setup your AP to be a Java module and to inform your users to use the Gradle android-apt plugin by Hugo Visser
  • 30. PROBLEM 2 Both your library and your AP might depend on the annotations
  • 31. SOLUTION Setup your annotations to be another Java module on which both the library and the AP depend on
  • 32. PROBLEM 3 Now the Javadoc of your library does not include the annotations
  • 33. SOLUTION android.libraryVariants.all { variant -> task("javadoc${variant.name.capitalize()}", type: Javadoc) { description "Generates Javadoc for $variant.name." group 'Docs' source = variant.javaCompile.source source "../annotations/src/main/java" // <-- THIS! ext.androidJar = files(project.android.getBootClasspath()) classpath = files(variant.javaCompile.classpath.files) + ext.androidJar exclude '**/BuildConfig.java' exclude '**/R.java' } }
  • 34. ANDROID LIBRARIES THAT USE AP ▸ ButterKnife ▸ Dagger ▸ Parceler ▸ Realm