SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Downloaden Sie, um offline zu lesen
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?

Weitere ähnliche Inhalte

Was ist angesagt?

#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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 

Kürzlich hochgeladen (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 

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