SlideShare a Scribd company logo
1 of 31
Download to read offline
Annotation processing
in Android
Randy Hu @ 91 APP
Library use Annotation
Processor
• AndroidAnnotation
• http://androidannotations.org/
• ButterKnife
• https://github.com/JakeWharton/butterknife
• Dagger
• http://square.github.io/dagger/
Library (not) use Annotation
Processor
• Retrofit
• http://square.github.io/retrofit/
• galette
• https://github.com/uPhyca/GAlette
Annotation
@Target(ElementType.METHOD)

@Retention(RetentionPolicy.SOURCE)

public @interface Override {

}
• Target
• Where can annotate
• Retention
• Where to store
Target
• TYPE
• FIELD
• METHOD
• PARAMETER
• CONSTRUCTOR
• LOCAL_VARIABLE
• ANNOTATION_TYPE
• PACKAGE
Retention
• SOURCE
• CLASS
• RUNTIME
• used in Reflection
• java.lang.reflect.AnnotatedElement
Parameters
@Retention(RetentionPolicy.SOURCE)

@Target(ElementType.TYPE)

public @interface TypeAnnotation {

String[] uris() default {};

int count() default 0;

String value() default "";

AnnotationEnum enu() default AnnotationEnum.Enum1;

}
Usage:
@TypeAnnotation(uris={"MainActivity", "1"}, value="a", count=20)

public class MainActivity extends ActionBarActivity {
......
}
Write Annotation
Processor ( with your bare hand )
Modules
• annotations
• Annotations can be used in app & annotation-
processor
• app
• main
• processor
• process annotations annotated in app
Dependency - top level
buildscript {

repositories {

jcenter()

}

dependencies {

classpath 'com.android.tools.build:gradle:1.2.3'

classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'

}

}

Dependency - processor
dependencies {

...

compile project(':annotation')
}
Dependency - app
apply plugin: 'com.android.application'

apply plugin: 'android-apt'
...
...
dependencies {
...

apt project(':annotationprocessor')

compile project(':annotation')

}
annotations
@Retention(RetentionPolicy.SOURCE)

@Target(ElementType.METHOD)

public @interface MethodAnnotation {

String parameterName();

String parameterValue();

}
app
@MethodAnnotation(parameterName = "input", parameterValue = "inputValue")

public void stringContact(String input) {



}
processor - basic setting
// Supported Annotation
@SupportedAnnotationTypes({"me.lunacat.annotations.MethodAnnotation"})

public class AnnotationProcessor extends AbstractProcessor {
private Filer filer;

private Messager messager;
@Override

public synchronized void init(ProcessingEnvironment env){

super.init(env);

filer = processingEnv.getFiler(); // File instance

messager = processingEnv.getMessager(); // Logger

}
@Override

public SourceVersion getSupportedSourceVersion() {

return SourceVersion.latestSupported();

}
// processing function
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment
roundEnv) {}
}
processor- gather annotations
@Override

public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
ArrayList<MethodAnnotation> methodAnnotations = new ArrayList<>();

for (Element e : roundEnv.getElementsAnnotatedWith(MethodAnnotation.class))
{

MethodAnnotation annot = e.getAnnotation(MethodAnnotation.class);

methodAnnotations.add(annot);

}
generateJavaFile(methodAnnotations);
}
processor - generate code
private void generateJavaFile(ArrayList<MethodAnnotation> methodAnnotations) throws
IOException {
// create ExtraClass with annotation content
JavaFileObject source = filer.createSourceFile(“in.test.AnnotationGenClass”);

Writer writer = source.openWriter();

try {

PrintWriter pw = new PrintWriter(writer);

pw.println("package in.test;");

pw.println("public class AnnotationGenClass {");

for(MethodAnnotation annot: methodAnnotations) {

pw.println("public static final void " + annot.parameterName() + "() {}");

}

pw.println("}");

pw.flush();

pw.close();

}

finally {

writer.close();

}
}
processor - generate resources
private void generateJavaFile(ArrayList<MethodAnnotation> methodAnnotations) throws
IOException {
// create method.txt with annotation contents
FileObject file = filer.createResource(
StandardLocation.SOURCE_OUTPUT,

"",
"methods.txt",
null);


writer = file.openWriter();

try {

PrintWriter pw = new PrintWriter(writer);

for(MethodAnnotation annot: methodAnnotations) {

pw.println(annot.parameterName());

}

pw.flush();

pw.close();

}

finally {

writer.close();

}
}
processor - create meta-data
create file: javax.annotation.processing.Processor
file content: me.lunacat.AnnotationProcessor
Write Annotation
Processor ( with tools )
Generate Code - filer
private void generateJavaFile(ArrayList<MethodAnnotation> methodAnnotations) throws
IOException {
// create ExtraClass with annotation content
JavaFileObject source = filer.createSourceFile(“in.test.AnnotationGenClass”);

Writer writer = source.openWriter();

try {

PrintWriter pw = new PrintWriter(writer);

pw.println("package in.test;");

pw.println("public class AnnotationGenClass{");

for(MethodAnnotation annot: methodAnnotations) {

pw.println("public static final void " + annot.parameterName() + "() {}");

}

pw.println("}");

pw.flush();

pw.close();

}

finally {

writer.close();

}
}
Generate Code - JavaPoet
for(MethodAnnotation annot: methodAnnotations) {

MethodSpec dumpMethod = MethodSpec

.methodBuilder(annot.parameterName())

.addModifiers(Modifier.FINAL, Modifier.STATIC, Modifier.PUBLIC)

.returns(void.class)

.build();

dumpMethods.add(dumpMethod);

}

// create class

TypeSpec.Builder classBuilder = TypeSpec

.classBuilder("AnnotationGenClass")

.addModifiers(Modifier.PUBLIC);

if ( dumpMethods != null ) {

classBuilder.addMethods(dumpMethods);

}

JavaFile.builder("me.lunacat.annotationgent", classBuilder.build())

.build()

.writeTo(filer);
with dependencies
dependencies {

compile 'com.squareup:javapoet:1.1.0'
}
MetaData - bare hand
create file: java.annotation.processing.Processor
file content: me.lunacat.AnnotationProcessor
MetaData - Auto
• Auto
• https://github.com/google/auto
@AutoService(Processor.class)

public class AnnotationProcessor extends AbstractProcessor {
}
With dependency:
dependencies {
compile 'com.google.auto.service:auto-service:1.0-rc2'

}
Testing
JavaFileObject sampleActivity = JavaFileObjects

.forSourceString("SampleActivity", "package com.example;"

+ "import me.lunacat.annotations.TypeAnnotation; "

+ "@Type("airbnb://example.com/deepLink") public class SampleActivity {}”);
// sampleActivity with AnnotationProcessor with generate source like
assert_().about(javaSource())

.that(sampleActivity)

.processedWith(new AnnotationProcessor())

.compilesWithoutError()

.and()

.generatesSources(

JavaFileObjects.forResource("AnnotationGenClass.java"),

JavaFileObjects.forSourceString("AnnotationGenClass",

"package.."));
with dependencies
dependencies {
testCompile 'com.google.testing.compile:compile-testing:0.6'
}
Debug
Debug
messager.printMessage(Diagnostic.Kind.WARNING, "no annot found");
Pass Parameter to
Processor
Pass Parameter to Processor
apt {
arguments{
host "http://www.123456789.host/"
}
}
build.gradle (app)
Processor
public synchronized void init(ProcessingEnvironment env) {

String host = env.getOptions().get("host");
}
References
• Annotation 101
• http://brianattwell.com/android-annotation-processing-
pojo-string-generator/
• http://hannesdorfmann.com/annotation-processing/
annotationprocessing101/#processing-rounds
• Debug Annotation Processor
• https://turbomanage.wordpress.com/2014/06/09/
debug-an-annotation-processor-with-intellij-and-gradle/

More Related Content

What's hot

DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
Graham Dumpleton
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
Hideaki Ohno
 

What's hot (13)

Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
Talk about Testing at vienna.rb meetup #2 on Apr 12th, 2013
 
Reactive Web - Servlet & Async, Non-blocking I/O
Reactive Web - Servlet & Async, Non-blocking I/OReactive Web - Servlet & Async, Non-blocking I/O
Reactive Web - Servlet & Async, Non-blocking I/O
 
Expression Language 3.0
Expression Language 3.0Expression Language 3.0
Expression Language 3.0
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeUsing Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
 
Perl basics for pentesters part 2
Perl basics for pentesters part 2Perl basics for pentesters part 2
Perl basics for pentesters part 2
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
 
6 more things about Perl 6
6 more things about Perl 66 more things about Perl 6
6 more things about Perl 6
 
Perl Basics for Pentesters Part 1
Perl Basics for Pentesters Part 1Perl Basics for Pentesters Part 1
Perl Basics for Pentesters Part 1
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)
 

Viewers also liked

Reading Comprehension Strategies list
Reading Comprehension Strategies listReading Comprehension Strategies list
Reading Comprehension Strategies list
Andrea Hnatiuk
 
12.18.2013, REPORT, Selected Macroeconomic Indicators, International Monetar...
12.18.2013, REPORT, Selected Macroeconomic Indicators,  International Monetar...12.18.2013, REPORT, Selected Macroeconomic Indicators,  International Monetar...
12.18.2013, REPORT, Selected Macroeconomic Indicators, International Monetar...
The Business Council of Mongolia
 

Viewers also liked (20)

Don't reinvent the wheel, use libraries
Don't reinvent the wheel, use librariesDon't reinvent the wheel, use libraries
Don't reinvent the wheel, use libraries
 
ButterKnife
ButterKnifeButterKnife
ButterKnife
 
Reading Comprehension Strategies list
Reading Comprehension Strategies listReading Comprehension Strategies list
Reading Comprehension Strategies list
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Annotating Text: A Powerful Reading Tool
Annotating Text: A Powerful Reading ToolAnnotating Text: A Powerful Reading Tool
Annotating Text: A Powerful Reading Tool
 
How to annotate
How to annotateHow to annotate
How to annotate
 
How to annotate non fiction text
How to annotate non fiction textHow to annotate non fiction text
How to annotate non fiction text
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner Walkthrough
 
портфоліо душнюк лілія
портфоліо душнюк ліліяпортфоліо душнюк лілія
портфоліо душнюк лілія
 
13.08.2010, NEWSWIRE, Issue 131
13.08.2010, NEWSWIRE, Issue 13113.08.2010, NEWSWIRE, Issue 131
13.08.2010, NEWSWIRE, Issue 131
 
Rpp bab kebersihan
Rpp bab kebersihanRpp bab kebersihan
Rpp bab kebersihan
 
12.18.2013, REPORT, Selected Macroeconomic Indicators, International Monetar...
12.18.2013, REPORT, Selected Macroeconomic Indicators,  International Monetar...12.18.2013, REPORT, Selected Macroeconomic Indicators,  International Monetar...
12.18.2013, REPORT, Selected Macroeconomic Indicators, International Monetar...
 
20.10.2011 Mongolia mining cluster development initiative, Mr Ser-Od
20.10.2011 Mongolia mining cluster development initiative, Mr Ser-Od20.10.2011 Mongolia mining cluster development initiative, Mr Ser-Od
20.10.2011 Mongolia mining cluster development initiative, Mr Ser-Od
 
Marc
MarcMarc
Marc
 
15.12.2014, Discussions on permit law, Government of Mongolia
15.12.2014, Discussions on permit law, Government of Mongolia15.12.2014, Discussions on permit law, Government of Mongolia
15.12.2014, Discussions on permit law, Government of Mongolia
 
28.03.2014, NEWSWIRE, Issue 318
28.03.2014, NEWSWIRE, Issue 31828.03.2014, NEWSWIRE, Issue 318
28.03.2014, NEWSWIRE, Issue 318
 
18.03.2013 Economic impact of draft minerals law, Dr. Brian Fisher
18.03.2013 Economic impact of draft minerals law, Dr. Brian Fisher18.03.2013 Economic impact of draft minerals law, Dr. Brian Fisher
18.03.2013 Economic impact of draft minerals law, Dr. Brian Fisher
 
Verifone Q4 2016 Earnings
Verifone Q4 2016 EarningsVerifone Q4 2016 Earnings
Verifone Q4 2016 Earnings
 

Similar to Annotation processing in android

EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
Enterprise PHP Center
 

Similar to Annotation processing in android (20)

Write code that writes code! A beginner's guide to Annotation Processing - Ja...
Write code that writes code! A beginner's guide to Annotation Processing - Ja...Write code that writes code! A beginner's guide to Annotation Processing - Ja...
Write code that writes code! A beginner's guide to Annotation Processing - Ja...
 
Write code that writes code!
Write code that writes code!Write code that writes code!
Write code that writes code!
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Annotations Processor Tools (APT)
Annotations Processor Tools (APT)Annotations Processor Tools (APT)
Annotations Processor Tools (APT)
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With Spoon
 
Michael Häusler – Everyday flink
Michael Häusler – Everyday flinkMichael Häusler – Everyday flink
Michael Häusler – Everyday flink
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing Fanatic
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6
 
Static Analysis of PHP Code – IPC Berlin 2016
Static Analysis of PHP Code – IPC Berlin 2016Static Analysis of PHP Code – IPC Berlin 2016
Static Analysis of PHP Code – IPC Berlin 2016
 
Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code gen
 
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPIPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web Applications
 

Recently uploaded

result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 

Annotation processing in android

  • 2.
  • 3. Library use Annotation Processor • AndroidAnnotation • http://androidannotations.org/ • ButterKnife • https://github.com/JakeWharton/butterknife • Dagger • http://square.github.io/dagger/
  • 4. Library (not) use Annotation Processor • Retrofit • http://square.github.io/retrofit/ • galette • https://github.com/uPhyca/GAlette
  • 5. Annotation @Target(ElementType.METHOD)
 @Retention(RetentionPolicy.SOURCE)
 public @interface Override {
 } • Target • Where can annotate • Retention • Where to store
  • 6. Target • TYPE • FIELD • METHOD • PARAMETER • CONSTRUCTOR • LOCAL_VARIABLE • ANNOTATION_TYPE • PACKAGE
  • 7. Retention • SOURCE • CLASS • RUNTIME • used in Reflection • java.lang.reflect.AnnotatedElement
  • 8. Parameters @Retention(RetentionPolicy.SOURCE)
 @Target(ElementType.TYPE)
 public @interface TypeAnnotation {
 String[] uris() default {};
 int count() default 0;
 String value() default "";
 AnnotationEnum enu() default AnnotationEnum.Enum1;
 } Usage: @TypeAnnotation(uris={"MainActivity", "1"}, value="a", count=20)
 public class MainActivity extends ActionBarActivity { ...... }
  • 9. Write Annotation Processor ( with your bare hand )
  • 10. Modules • annotations • Annotations can be used in app & annotation- processor • app • main • processor • process annotations annotated in app
  • 11. Dependency - top level buildscript {
 repositories {
 jcenter()
 }
 dependencies {
 classpath 'com.android.tools.build:gradle:1.2.3'
 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
 }
 }

  • 12. Dependency - processor dependencies {
 ...
 compile project(':annotation') }
  • 13. Dependency - app apply plugin: 'com.android.application'
 apply plugin: 'android-apt' ... ... dependencies { ...
 apt project(':annotationprocessor')
 compile project(':annotation')
 }
  • 15. app @MethodAnnotation(parameterName = "input", parameterValue = "inputValue")
 public void stringContact(String input) {
 
 }
  • 16. processor - basic setting // Supported Annotation @SupportedAnnotationTypes({"me.lunacat.annotations.MethodAnnotation"})
 public class AnnotationProcessor extends AbstractProcessor { private Filer filer;
 private Messager messager; @Override
 public synchronized void init(ProcessingEnvironment env){
 super.init(env);
 filer = processingEnv.getFiler(); // File instance
 messager = processingEnv.getMessager(); // Logger
 } @Override
 public SourceVersion getSupportedSourceVersion() {
 return SourceVersion.latestSupported();
 } // processing function public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {} }
  • 17. processor- gather annotations @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { ArrayList<MethodAnnotation> methodAnnotations = new ArrayList<>();
 for (Element e : roundEnv.getElementsAnnotatedWith(MethodAnnotation.class)) {
 MethodAnnotation annot = e.getAnnotation(MethodAnnotation.class);
 methodAnnotations.add(annot);
 } generateJavaFile(methodAnnotations); }
  • 18. processor - generate code private void generateJavaFile(ArrayList<MethodAnnotation> methodAnnotations) throws IOException { // create ExtraClass with annotation content JavaFileObject source = filer.createSourceFile(“in.test.AnnotationGenClass”);
 Writer writer = source.openWriter();
 try {
 PrintWriter pw = new PrintWriter(writer);
 pw.println("package in.test;");
 pw.println("public class AnnotationGenClass {");
 for(MethodAnnotation annot: methodAnnotations) {
 pw.println("public static final void " + annot.parameterName() + "() {}");
 }
 pw.println("}");
 pw.flush();
 pw.close();
 }
 finally {
 writer.close();
 } }
  • 19. processor - generate resources private void generateJavaFile(ArrayList<MethodAnnotation> methodAnnotations) throws IOException { // create method.txt with annotation contents FileObject file = filer.createResource( StandardLocation.SOURCE_OUTPUT,
 "", "methods.txt", null); 
 writer = file.openWriter();
 try {
 PrintWriter pw = new PrintWriter(writer);
 for(MethodAnnotation annot: methodAnnotations) {
 pw.println(annot.parameterName());
 }
 pw.flush();
 pw.close();
 }
 finally {
 writer.close();
 } }
  • 20. processor - create meta-data create file: javax.annotation.processing.Processor file content: me.lunacat.AnnotationProcessor
  • 22. Generate Code - filer private void generateJavaFile(ArrayList<MethodAnnotation> methodAnnotations) throws IOException { // create ExtraClass with annotation content JavaFileObject source = filer.createSourceFile(“in.test.AnnotationGenClass”);
 Writer writer = source.openWriter();
 try {
 PrintWriter pw = new PrintWriter(writer);
 pw.println("package in.test;");
 pw.println("public class AnnotationGenClass{");
 for(MethodAnnotation annot: methodAnnotations) {
 pw.println("public static final void " + annot.parameterName() + "() {}");
 }
 pw.println("}");
 pw.flush();
 pw.close();
 }
 finally {
 writer.close();
 } }
  • 23. Generate Code - JavaPoet for(MethodAnnotation annot: methodAnnotations) {
 MethodSpec dumpMethod = MethodSpec
 .methodBuilder(annot.parameterName())
 .addModifiers(Modifier.FINAL, Modifier.STATIC, Modifier.PUBLIC)
 .returns(void.class)
 .build();
 dumpMethods.add(dumpMethod);
 }
 // create class
 TypeSpec.Builder classBuilder = TypeSpec
 .classBuilder("AnnotationGenClass")
 .addModifiers(Modifier.PUBLIC);
 if ( dumpMethods != null ) {
 classBuilder.addMethods(dumpMethods);
 }
 JavaFile.builder("me.lunacat.annotationgent", classBuilder.build())
 .build()
 .writeTo(filer); with dependencies dependencies {
 compile 'com.squareup:javapoet:1.1.0' }
  • 24. MetaData - bare hand create file: java.annotation.processing.Processor file content: me.lunacat.AnnotationProcessor
  • 25. MetaData - Auto • Auto • https://github.com/google/auto @AutoService(Processor.class)
 public class AnnotationProcessor extends AbstractProcessor { } With dependency: dependencies { compile 'com.google.auto.service:auto-service:1.0-rc2'
 }
  • 26. Testing JavaFileObject sampleActivity = JavaFileObjects
 .forSourceString("SampleActivity", "package com.example;"
 + "import me.lunacat.annotations.TypeAnnotation; "
 + "@Type("airbnb://example.com/deepLink") public class SampleActivity {}”); // sampleActivity with AnnotationProcessor with generate source like assert_().about(javaSource())
 .that(sampleActivity)
 .processedWith(new AnnotationProcessor())
 .compilesWithoutError()
 .and()
 .generatesSources(
 JavaFileObjects.forResource("AnnotationGenClass.java"),
 JavaFileObjects.forSourceString("AnnotationGenClass",
 "package..")); with dependencies dependencies { testCompile 'com.google.testing.compile:compile-testing:0.6' }
  • 27. Debug
  • 30. Pass Parameter to Processor apt { arguments{ host "http://www.123456789.host/" } } build.gradle (app) Processor public synchronized void init(ProcessingEnvironment env) {
 String host = env.getOptions().get("host"); }
  • 31. References • Annotation 101 • http://brianattwell.com/android-annotation-processing- pojo-string-generator/ • http://hannesdorfmann.com/annotation-processing/ annotationprocessing101/#processing-rounds • Debug Annotation Processor • https://turbomanage.wordpress.com/2014/06/09/ debug-an-annotation-processor-with-intellij-and-gradle/