SlideShare une entreprise Scribd logo
1  sur  36
Télécharger pour lire hors ligne
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?

Contenu connexe

Tendances

#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML SchemaRaji Ghawi
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - PraticalsFahad Shaikh
 
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 ProcessingJintin 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 modulesRafael Winterhalter
 

Tendances (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
 

En vedette

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 NationsSiena 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 2016Yuki Anzai
 
ChromeとAndroidの過去・現在・未来
ChromeとAndroidの過去・現在・未来ChromeとAndroidの過去・現在・未来
ChromeとAndroidの過去・現在・未来Shinobu Okano
 
Android,Brillo,ChromeOS
Android,Brillo,ChromeOSAndroid,Brillo,ChromeOS
Android,Brillo,ChromeOSl_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 CanvasMima Yuki
 
怖くないGradle設定とBazel
怖くないGradle設定とBazel怖くないGradle設定とBazel
怖くないGradle設定とBazelshimada tatsuya
 
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 KnowledgeShinobu Okano
 
最速でリリースするためのAndroidアプリデザイン
最速でリリースするためのAndroidアプリデザイン最速でリリースするためのAndroidアプリデザイン
最速でリリースするためのAndroidアプリデザインNaoki Aoyama
 
Android lint-srp-practice
Android lint-srp-practiceAndroid lint-srp-practice
Android lint-srp-practicecch-robo
 
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介minneにおけるテスト〜リリース〜リリース後にやっている事の紹介
minneにおけるテスト〜リリース〜リリース後にやっている事の紹介Masataka Kono
 
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigiReact Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigi
React Nativeはクロスプラットフォームモバイルアプリ開発の夢を見るか #DroidKaigiYukiya Nakagawa
 

En vedette (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
 

Similaire à Annotation Processing in Android

Java for Mainframers
Java for MainframersJava for Mainframers
Java for MainframersRich Helton
 
Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Brian S. Paskin
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginersdivaskrgupta007
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
Introduction
IntroductionIntroduction
Introductionrichsoden
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_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.docxssuser454af01
 
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 processorBartosz Kosarzycki
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Final Project Presentation
Final Project PresentationFinal Project Presentation
Final Project Presentationzroserie
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to JavaSMIJava
 

Similaire à 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
 

Dernier

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Dernier (20)

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

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