SlideShare uma empresa Scribd logo
1 de 36
Baixar para ler offline
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?

Mais conteúdo relacionado

Mais procurados

#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
 

Mais procurados (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
 

Destaque

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
 

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

Semelhante a 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
 

Semelhante a 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
 

Último

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
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
 

Último (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
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
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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 ...
 

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