SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Downloaden Sie, um offline zu lesen
Java Annotation Processing
A Beginner Walkthrough
Mahfuz Islam Bhuiyan
Software Engineer, Genweb2
What’s Annotation?
● Provide meta-data for Java code
● Can describe usage of an element, e.g. @Deprecated
● Can describe the nature of an element, e.g. @WebService
● and many more
Built-in Java Annotations
@Deprecated
@Override
@SuppressWarning
Custom Annotation
public @interface MyAnnotation { // @interface tells Java that it’s a custom annotation
String value();
String name();
int age();
String[] newNames();
}
Custom Annotation
@MyAnnotation(
value="Test123456",
name=" Oveget ",
age=37,
newNames={"Rishi", "Farzana"}
)
public class MyClass {
}
Custom Annotation
public @interface MyAnnotation {
String value() default "";
String name() default " The Sufi ";
int age();
String[] newNames();
}
Annotation Processing Trends
● Remove boilerplate
● Inject Source Code
● Validate Fields, Methods, Class etc
Annotation Processing Facts
● Part of javac
● Introduced in Java 5
● Run at Compile Time(!)
● Own JVM
● Native Java code
● No Reflection(by default)
Java Reflection
● Makes it possible to inspect classes, interfaces, fields and methods at runtime,
without knowing the names of the classes, methods etc. at compile time.
● Can instantiate new objects, invoke methods and get/set field values using
reflection.
Java Reflections
Method[] methods = MyObject.class.getMethods();
for(Method method : methods){
System.out.println("method = " + method.getName());
}
Java Reflections
Class aClass = MyObject.class
Field field = aClass.getField("someField");
MyObject objectInstance = new MyObject();
Object value = field.get(objectInstance);
field.set(objetInstance, value);
@Retention
@Retention(RetentionPolicy.RUNTIME) // Allows the annotation to be available at Runtime
@Target({ElementType.METHOD})
public @interface MyAnnotation { // Yes, we can apply annotation over another annotation
String value() default "";
}
Annotation Processing Limitations
● Generate only new files
● Can’t manipulate already existing files(But byte manipulation possible with
sacrificing debugging capability)
Create Your Own Annotation Processor
1. Extends AbstractProcessor
2. Register the processor with javac
Extending Abstract Processor
public class MyProcessor extends AbstractProcessor {
@Override
public synchronized void init(ProcessingEnvironment env){}
@Override
public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { }
@Override
public Set<String> getSupportedAnnotationTypes() { }
@Override
public SourceVersion getSupportedSourceVersion() { }
}
Extending Abstract Processor
@SupportedSourceVersion(SourceVersion.latestSupported())
@SupportedAnnotationTypes({
// Set of full qualified annotation type names
})
public class MyProcessor extends AbstractProcessor {
@Override
public synchronized void init(ProcessingEnvironment env){ }
@Override
public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { }
}
Extending Abstract Processor
@SupportedSourceVersion(SourceVersion.latestSupported())
@SupportedAnnotationTypes({
// Set of full qualified annotation type names
})
public class MyProcessor extends AbstractProcessor {
@Override
public synchronized void init(ProcessingEnvironment env){ }
// We need to get our hands dirty with following method
@Override
public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { }
}
Register the Processor
1. Create a .jar file with our Annotation Processor Java file
2. Provide a special file called javax.annotation.processing.Processor located in
META-INF/services in your .jar file
3. Within the javax.annotation.processing.Processor , there should be the fully
qualified names of the processors contained in the Jar file(like, com.example.
MyProcessor.class)
So, it’ll look like
MyProcessor.jar
=> com
=> example
=> MyProcessor.class
=> META-INF
=> services
=> javax.annotation.processing.Processor
Validate a Class with Custom Annotation
Processor
Annotation
import com.example;
public @interface ConstructorCheck{
}
Annotation Processor
@SupportedSourceVersion(SourceVersion.latestSupported())
@SupportedAnnotationTypes({"com.example.ConstructorCheck"})
}
public class MyProcessor extends AbstractProcessor {
@Override
public synchronized void init(ProcessingEnvironment env){ }
@Override
public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { }
}
init
ProcessingEnvironment processingEnv;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.processingEnv = processingEnv;
}
ProcessingEnvironment
● getElementUtils => Elements
● getTypeUtils => Types
● getFiler => Filer
● getMessager => Messager
Element
● Is not a class per se !
● Contains value that can be of Class, Interface etc
Element
public class User{ // TypeElement
private String name; // VariableElement
private Person personObj; // VariableElement
public User(){} // ExecutableElement
public boolean isUserHasNID(){ // ExecutableElement
/*...*/
}
}
TypeMirror
● Provide some meta data about Element
● Get to know the class inheritance hierarchy, for instance
process
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
checkEntityAnnotatedElements(roundEnv);
return false; // true if we want to stop processor’s further execution
}
private void checkEntityAnnotatedElements(RoundEnvironment roundEnv) {
Set <? extends Element > entityAnnotated = roundEnv.getElementsAnnotatedWith(CheckConstructor.
class);
for (TypeElement typeElement: ElementFilter.typesIn(entityAnnotated)) {
for (ExecutableElement constructor: ElementFilter.constructorsIn(typeElement.
getEnclosedElements())) {
List <? extends VariableElement > parameters = constructor.getParameters();
if (parameters.isEmpty()) return;
}
AnnotationMirror entityAnnotation = getAnnotation(typeElement, entityType.type);
processingEnv.getMessager().printMessage(Kind.ERROR,
"missing no argument constructor", typeElement, entityAnnotation);
}
}
Automatic Source Code Generating Tool
JavaPoet
● JavaPoet is a API for generating java source files.
● It can be useful when doing things such as annotation processing or interacting
with metadata files.
JavaPoet
Here goes a plain simple java class
package com.example.helloworld;
public final class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, JavaPoet!");
}
}
JavaPoet
With JavaPoet, it’ll look like this.
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(System.out)
Some Cool Annotation Based Tools
Project Lombok
● Project Lombok greatly reduces the number of lines of boilerplate code
Dagger 2
● Dagger 2 is a fork from Dagger 1 under heavy development by Google
● Dependency Injection design pattern without the burden of writing the
boilerplate
● No reflection at all
● Achieved 13% performance boost over Dagger 1
Butter Knife
● Butter Knife injects views on Android
● Reduce boilerplate codes
● Support Resource and Event binding too
Butter Knife
class ExampleActivity extends Activity {
TextView title, subtitle;
EditText inputTitle, inputSubTitle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
title = (TextView)findViewById(R.id.title);
subtitle = (TextView)findViewById(R.id.subtitle);
inputTitle = (EditText)findViewById(R.id.inputTitle);
inputSubtitle = (EditText)findViewById(R.id.inputSubTitle);
}
}
Butter Knife
class ExampleActivity extends Activity {
@Bind(R.id.title) TextView title;
@Bind(R.id.subtitle) TextView subtitle;
@Bind(R.id.subtitle) EditText inputTitle;
@Bind(R.id.subtitle) EditText inputSubtitle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.bind(this);
}
}
References
● Annotation Processing 101
● Code Generation Using Annotation Processor in Java
● Writing Annotation Processors to aid your development process
● Android Tech Talk: Annotation Processing Boilerplate Destruction
● Java Annotation Processor Tutorial
● Java Annotations
● Official Java Annotation Processor Documentation
@thankYou

Weitere ähnliche Inhalte

Was ist angesagt?

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 

Was ist angesagt? (20)

Async ... Await – concurrency in java script
Async ... Await – concurrency in java scriptAsync ... Await – concurrency in java script
Async ... Await – concurrency in java script
 
Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
HTML/CSS/java Script/Jquery
HTML/CSS/java Script/JqueryHTML/CSS/java Script/Jquery
HTML/CSS/java Script/Jquery
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
Ajax
AjaxAjax
Ajax
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 

Andere mochten auch

Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
олександра присташ (2)
олександра присташ (2)олександра присташ (2)
олександра присташ (2)
Olexandra Prystash
 

Andere mochten auch (20)

Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Annotations in Java
Annotations in JavaAnnotations in Java
Annotations in Java
 
Java annotation
Java annotationJava annotation
Java annotation
 
Type Annotations in Java 8
Type Annotations in Java 8 Type Annotations in Java 8
Type Annotations in Java 8
 
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
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Java Annotation
Java AnnotationJava Annotation
Java Annotation
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
олександра присташ (2)
олександра присташ (2)олександра присташ (2)
олександра присташ (2)
 
Innovations™ Magazine VII NO.2 2015 - Chinese
Innovations™ Magazine VII NO.2 2015 - ChineseInnovations™ Magazine VII NO.2 2015 - Chinese
Innovations™ Magazine VII NO.2 2015 - Chinese
 

Ähnlich wie Java Annotation Processing: A Beginner Walkthrough

Ähnlich wie Java Annotation Processing: A Beginner Walkthrough (20)

比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Java Annotations and Pre-processing
Java  Annotations and Pre-processingJava  Annotations and Pre-processing
Java Annotations and Pre-processing
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the question
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With Spoon
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Struts2 notes
Struts2 notesStruts2 notes
Struts2 notes
 
Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation Processing
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
 
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
 
Devoxx 2012 hibernate envers
Devoxx 2012   hibernate enversDevoxx 2012   hibernate envers
Devoxx 2012 hibernate envers
 
Aspect oriented programming with spring
Aspect oriented programming with springAspect oriented programming with spring
Aspect oriented programming with spring
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
 

Kürzlich hochgeladen

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+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
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Kürzlich hochgeladen (20)

Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
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
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
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
 
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
 
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
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
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-...
 
+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...
 
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 ...
 
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
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
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
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 

Java Annotation Processing: A Beginner Walkthrough

  • 1. Java Annotation Processing A Beginner Walkthrough Mahfuz Islam Bhuiyan Software Engineer, Genweb2
  • 2. What’s Annotation? ● Provide meta-data for Java code ● Can describe usage of an element, e.g. @Deprecated ● Can describe the nature of an element, e.g. @WebService ● and many more
  • 4. Custom Annotation public @interface MyAnnotation { // @interface tells Java that it’s a custom annotation String value(); String name(); int age(); String[] newNames(); }
  • 5. Custom Annotation @MyAnnotation( value="Test123456", name=" Oveget ", age=37, newNames={"Rishi", "Farzana"} ) public class MyClass { }
  • 6. Custom Annotation public @interface MyAnnotation { String value() default ""; String name() default " The Sufi "; int age(); String[] newNames(); }
  • 7. Annotation Processing Trends ● Remove boilerplate ● Inject Source Code ● Validate Fields, Methods, Class etc
  • 8. Annotation Processing Facts ● Part of javac ● Introduced in Java 5 ● Run at Compile Time(!) ● Own JVM ● Native Java code ● No Reflection(by default)
  • 9.
  • 10. Java Reflection ● Makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. ● Can instantiate new objects, invoke methods and get/set field values using reflection.
  • 11. Java Reflections Method[] methods = MyObject.class.getMethods(); for(Method method : methods){ System.out.println("method = " + method.getName()); }
  • 12. Java Reflections Class aClass = MyObject.class Field field = aClass.getField("someField"); MyObject objectInstance = new MyObject(); Object value = field.get(objectInstance); field.set(objetInstance, value);
  • 13. @Retention @Retention(RetentionPolicy.RUNTIME) // Allows the annotation to be available at Runtime @Target({ElementType.METHOD}) public @interface MyAnnotation { // Yes, we can apply annotation over another annotation String value() default ""; }
  • 14. Annotation Processing Limitations ● Generate only new files ● Can’t manipulate already existing files(But byte manipulation possible with sacrificing debugging capability)
  • 15. Create Your Own Annotation Processor 1. Extends AbstractProcessor 2. Register the processor with javac
  • 16.
  • 17. Extending Abstract Processor public class MyProcessor extends AbstractProcessor { @Override public synchronized void init(ProcessingEnvironment env){} @Override public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { } @Override public Set<String> getSupportedAnnotationTypes() { } @Override public SourceVersion getSupportedSourceVersion() { } }
  • 18. Extending Abstract Processor @SupportedSourceVersion(SourceVersion.latestSupported()) @SupportedAnnotationTypes({ // Set of full qualified annotation type names }) public class MyProcessor extends AbstractProcessor { @Override public synchronized void init(ProcessingEnvironment env){ } @Override public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { } }
  • 19. Extending Abstract Processor @SupportedSourceVersion(SourceVersion.latestSupported()) @SupportedAnnotationTypes({ // Set of full qualified annotation type names }) public class MyProcessor extends AbstractProcessor { @Override public synchronized void init(ProcessingEnvironment env){ } // We need to get our hands dirty with following method @Override public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { } }
  • 20. Register the Processor 1. Create a .jar file with our Annotation Processor Java file 2. Provide a special file called javax.annotation.processing.Processor located in META-INF/services in your .jar file 3. Within the javax.annotation.processing.Processor , there should be the fully qualified names of the processors contained in the Jar file(like, com.example. MyProcessor.class)
  • 21. So, it’ll look like MyProcessor.jar => com => example => MyProcessor.class => META-INF => services => javax.annotation.processing.Processor
  • 22. Validate a Class with Custom Annotation Processor
  • 24. Annotation Processor @SupportedSourceVersion(SourceVersion.latestSupported()) @SupportedAnnotationTypes({"com.example.ConstructorCheck"}) } public class MyProcessor extends AbstractProcessor { @Override public synchronized void init(ProcessingEnvironment env){ } @Override public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { } }
  • 25. init ProcessingEnvironment processingEnv; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); this.processingEnv = processingEnv; }
  • 26. ProcessingEnvironment ● getElementUtils => Elements ● getTypeUtils => Types ● getFiler => Filer ● getMessager => Messager
  • 27. Element ● Is not a class per se ! ● Contains value that can be of Class, Interface etc
  • 28.
  • 29. Element public class User{ // TypeElement private String name; // VariableElement private Person personObj; // VariableElement public User(){} // ExecutableElement public boolean isUserHasNID(){ // ExecutableElement /*...*/ } }
  • 30. TypeMirror ● Provide some meta data about Element ● Get to know the class inheritance hierarchy, for instance
  • 31. process @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { checkEntityAnnotatedElements(roundEnv); return false; // true if we want to stop processor’s further execution }
  • 32. private void checkEntityAnnotatedElements(RoundEnvironment roundEnv) { Set <? extends Element > entityAnnotated = roundEnv.getElementsAnnotatedWith(CheckConstructor. class); for (TypeElement typeElement: ElementFilter.typesIn(entityAnnotated)) { for (ExecutableElement constructor: ElementFilter.constructorsIn(typeElement. getEnclosedElements())) { List <? extends VariableElement > parameters = constructor.getParameters(); if (parameters.isEmpty()) return; } AnnotationMirror entityAnnotation = getAnnotation(typeElement, entityType.type); processingEnv.getMessager().printMessage(Kind.ERROR, "missing no argument constructor", typeElement, entityAnnotation); } }
  • 33. Automatic Source Code Generating Tool
  • 34. JavaPoet ● JavaPoet is a API for generating java source files. ● It can be useful when doing things such as annotation processing or interacting with metadata files.
  • 35. JavaPoet Here goes a plain simple java class package com.example.helloworld; public final class HelloWorld { public static void main(String[] args) { System.out.println("Hello, JavaPoet!"); } }
  • 36. JavaPoet With JavaPoet, it’ll look like this. 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(System.out)
  • 37.
  • 38. Some Cool Annotation Based Tools
  • 39. Project Lombok ● Project Lombok greatly reduces the number of lines of boilerplate code
  • 40.
  • 41. Dagger 2 ● Dagger 2 is a fork from Dagger 1 under heavy development by Google ● Dependency Injection design pattern without the burden of writing the boilerplate ● No reflection at all ● Achieved 13% performance boost over Dagger 1
  • 42. Butter Knife ● Butter Knife injects views on Android ● Reduce boilerplate codes ● Support Resource and Event binding too
  • 43. Butter Knife class ExampleActivity extends Activity { TextView title, subtitle; EditText inputTitle, inputSubTitle; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); title = (TextView)findViewById(R.id.title); subtitle = (TextView)findViewById(R.id.subtitle); inputTitle = (EditText)findViewById(R.id.inputTitle); inputSubtitle = (EditText)findViewById(R.id.inputSubTitle); } }
  • 44. Butter Knife class ExampleActivity extends Activity { @Bind(R.id.title) TextView title; @Bind(R.id.subtitle) TextView subtitle; @Bind(R.id.subtitle) EditText inputTitle; @Bind(R.id.subtitle) EditText inputSubtitle; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ButterKnife.bind(this); } }
  • 45.
  • 46.
  • 47.
  • 48.
  • 49. References ● Annotation Processing 101 ● Code Generation Using Annotation Processor in Java ● Writing Annotation Processors to aid your development process ● Android Tech Talk: Annotation Processing Boilerplate Destruction ● Java Annotation Processor Tutorial ● Java Annotations ● Official Java Annotation Processor Documentation