SlideShare a Scribd company logo
1 of 35
CODE GENERATION WITH ANNOTATION
PROCESSORS:
STATE OF THE ART IN JAVA 9
[CON3282]
ABOUT THE SPEAKERS
Copyright © 2017 Accenture. All rights reserved. 2
Welcome to our session!
Julio Palma Vázquez
Member – Málaga JUG
Technology Architect – Accenture Technology
Accenture Global Java Champion
Accenture Delivery Center in Spain
Mountain biker, AD&D player, Sid Meier’s Civilization gamer,
LotR fan, …
@restalion
https://github.com/restalion
Jorge Hidalgo
Coordinator – Málaga JUG
Global Java Lead – Accenture Technology
Java, Architecture & DevOps Lead
Accenture Delivery Center in Spain
Father of two children, husband, whistle player, video gamer, sci-
fi ‘junkie’, Star Wars ‘addict’, Lego brick ‘wielder’, Raspberry Pi
fan, … LLAP!
@_deors
https://github.com/deors
• Overview of Annotations and Annotation Processors in Java
• What’s new in Java 9 APT API
• Learn how to create Annotation Processors
• Learn how to use Annotation Processors to generate source code
• Annotation Processors and Modules in Java 9
• With lots of examples and source code
CODE GENERATION IN THE JAVA COMPILER
Copyright © 2017 Accenture. All rights reserved. 3
Objetives for the session
Please raise your hands if you are familiar with Annotations, know how to use them or are
even capable of writing Annotation Types
POLL #1
Copyright © 2017 Accenture. All rights reserved. 4
ANNOTATIONS IN
JAVA LANGUAGE
Copyright © 2017 Accenture. All rights reserved. 5
• Annotations were first introduced in Java 5
• Add metadata capabilities to the Java language:
• Build/deployment information
• Configuration properties
• Compiler behavior
• Quality checks
• Dependency injection
• Persistence mapping
• ...
ANNOTATIONS IN THE JAVA LANGUAGE
Copyright © 2017 Accenture. All rights reserved. 6
History
• Annotations always appear before the annotated piece of code
• Annotations can ‘decorate’...
• Packages
• Types (classes, interfaces, enums, annotation types)
• Variables (class, instance and local variables)
• Constructors, methods and their parameters
• Generic type parameter (since Java 8)
• Any type use (since Java 8)
ANNOTATIONS IN THE JAVA LANGUAGE
Copyright © 2017 Accenture. All rights reserved. 7
Overview
• Can be grouped, nested, repeated... very powerful!
Map<@NonNull String, @NonEmpty List<@Readonly Document>> docStore;
• Annotations may be used just as a ‘marker’
@NonNull String email;
• They may contain name-value pairs, and arrays
@Author(name = "Albert",
created = "17/09/2010",
revision = 3,
reviewers = {"George", "Fred"})
public class SomeClass {...}
• Can be defined with default values, and then omitted when used
• When it has only one attribute named value, it can be omitted, too
@DatabaseTable(“MY_TABLE”) public class MyTable {...}
ANNOTATIONS IN THE JAVA LANGUAGE
Copyright © 2017 Accenture. All rights reserved. 8
Overview
HOW TO CREATE
ANNOTATIONS AND
ANNOTATION
PROCESSORS
Copyright © 2017 Accenture. All rights reserved. 9
Please raise your hands if you are familiar with Annotation Processors, their capabilities or
know how to write new ones
POLL #2
Copyright © 2017 Accenture. All rights reserved. 10
• A special type of interface
public @interface Author {
String name();
String created();
int revision() default 1;
String[] reviewers() default {};
}
• Only primitives, enum types, annotation types, String, Class and arrays of them are
allowed as elements
• May be annotated itself, i.e. to define the retention policy or targets
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE})
public @interface Author {...}
Can trigger custom actions at compile time managed by
Annotation Processors!
ANNOTATIONS
Copyright © 2017 Accenture. All rights reserved. 11
Create an Annotation Type
• Annotation Processor:
– Implements javax.annotation.processing.Processor
– Or extends javax.annotation.processing.AbstractProcessor
• May use three annotations to configure itself:
– jx.a.p.SupportedAnnotationTypes – Used to flag which Annotation Types are managed by the
– jx.a.p.SupportedSourceVersion – Used to flag the latest Java source level supported by the processor
– jx.a.p.SupportedOptions – Used to register custom parameters that may be passed through the
• TL;DR – Implement the process() method
ANNOTATION PROCESSORS
Copyright © 2017 Accenture. All rights reserved. 12
Annotation Processing API
• Annotation processing happens in ‘rounds’
• In each round, a subset of sources are compiled, and then
processors matching the annotations found on those sources
are called
• Processing ends when no more sources/annotations are
pending
• Processors may claim all annotation types with a wildcard
• process() method has two parameters:
– Set<? extends jx.lang.model.element.TypeElement> – subset of annotations being processed
– jx.a.p.RoundEnvironment – access to information about the current and previous round
ANNOTATION PROCESSORS
Copyright © 2017 Accenture. All rights reserved. 13
Annotation Processing API
jx.a.p.ProcessingEnvironment also provides access to the Filer utility that allows for easy file creation
• Files are placed in the right folder as required by the compiler settings
• Folder hierarchy matching the package name
JavaFileObject jfo = processingEnv.getFiler()
.createSourceFile(newClassQualifiedName);
Writer writer = jfo.openWriter();
...or...
JavaFileObject jfo = processingEnv.getFiler()
.createClassFile(newClassQualifiedName);
OutputStream os = jfo.openOutputStream();
ANNOTATION PROCESSORS
Copyright © 2017 Accenture. All rights reserved. 14
Creating Files
Annotation Processors leverage the standard services mechanism
• Package the processors in a Jar file
• Include file META-INF/services/javax.annotation.processing.Processor
• Contents are the fully qualified names of the bundled processors, one per line
ANNOTATION PROCESSORS
Copyright © 2017 Accenture. All rights reserved. 15
How the compiler knows?
Find more information about APT in JavaOne 2014 session:
https://www.slideshare.net/deors/javaone-2014-con2013-code-generation-in-the-java-compiler-annotation-processors-do-the-hard-work
https://www.youtube.com/watch?v=xswPPwYPAFM
ANNOTATION PROCESSORS
Copyright © 2017 Accenture. All rights reserved. 16
Running Annotation Processors
Multiple ways:
• javac
• Apache Maven builds
• Continuous Integration builds
• IDE
ANNOTATION PROCESSORS
Copyright © 2017 Accenture. All rights reserved. 17
Running Annotation Processors
ADAPT LEGACY APT
PROJECTS TO JAVA
9
Copyright © 2017 Accenture. All rights reserved. 18
• Update <java.version> tag in pom.xml
<java.version>1.9</java.version>
• Update version of maven-compiler-plugin
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.2</version>
• Upgrade the supported source version in Processor class
@SupportedAnnotationTypes(“com.foo.AnnotationSample")
@SupportedSourceVersion(SourceVersion.RELEASE_9)
public class AnnotationSampleProcessor
ADAPT LEGACY CODE
Copyright © 2017 Accenture. All rights reserved. 19
Upgrading your code to Java 9
• mvn clean install finish without errors:
ANNOTATIONS API IN JAVA 9
Copyright © 2017 Accenture. All rights reserved. 20
Upgrading your code to Java 9
DEMO
ANNOTATIONS API IN JAVA 9
Copyright © 2017 Accenture. All rights reserved. 21
Executing upgraded projects
Upgraded legacy code sample can be found in github:
https://github.com/deors/deors.demos.annotations
ADAPT LEGACY CODE
Copyright © 2017 Accenture. All rights reserved. 22
Upgrading your code to Java 9
WHAT’S NEW IN
JAVA 9 APT API
Copyright © 2017 Accenture. All rights reserved. 23
ANNOTATIONS API IN JAVA 9
Copyright © 2017 Accenture. All rights reserved. 24
Overview
• New @Generated Annotation
• To add information about the annotation processor, date, and comments:
@Generated(value = "com.foo.processors.SampleProcessor",
date = "2017-09-28T09:43:28.170886",
comments = "Sample")
• Processed as a subsequent step by the annotation processor.
• Two new methods in RoundEnvironment interface
• Simplify processing of multiple annotations
default Set<? extends Element> getElementsAnnotatedWithAny​(
Set<Class<? extends Annotation>> annotations);
default Set<? extends Element> getElementsAnnotatedWithAny​(
TypeElement... annotations);
ANNOTATIONS API IN JAVA 9
Copyright © 2017 Accenture. All rights reserved. 25
Overview
• Changes in all methods of Filer interface.
To manage files in a module, module name is prefixed to the type name and separated using a
“/” character, i.e.:
JavaFileObject jfo = processingEnv.getFiler().createSourceFile(
"com.foo/com.foo.Bar");
JavaFileObject jfo = processingEnv.getFiler().getResource(location,
"com.foo/com.foo", "Bar");
NEW FEATURES IN JAVA 9
Copyright © 2017 Accenture. All rights reserved. 26
• It’s a best practice to include this annotation in the generated code:
bw.append("@Generated(value = "" + this.getClass().getName() +
"" , date = "" +
LocalDateTime.now() +
"", comments = "Test generator")");
Generated Annotation
Comments
MUST have the name of
the code generator
Date when the source was generated
• During annotation processing,the Generated annotation will be found but nothing is done,
it’s just informational.
• Generated code:
NEW FEATURES IN JAVA 9
Copyright © 2017 Accenture. All rights reserved. 27
Generated Annotation
Name of the code generator
Generation date Comments
ANNOTATIONS API IN JAVA 9
Copyright © 2017 Accenture. All rights reserved. 28
Module
ANNOTATION
PROCESSORS AND
MODULES IN JAVA
9
Copyright © 2017 Accenture. All rights reserved. 29
ANNOTATION PROCESSORS AND MODULES
Copyright © 2017 Accenture. All rights reserved. 30
Creating classes in modules
• In previous examples we have three
different jar files:
• Annotation type
• Annotation processor
• classes that use annotations
• Dependencies are managed using the
regular classpath
30
annotation
annotation.processor
client
ANNOTATION PROCESSORS AND MODULES
Copyright © 2017 Accenture. All rights reserved. 31
Grouping classes in modules
• One module per jar file.
• Put a module-info.java file into each module.
• Each module-info file needs to define exported
packages and required modules.
annotation
annotation.processor
client
ANNOTATION PROCESSORS AND MODULES
Copyright © 2017 Accenture. All rights reserved. 32
Creating classes in modules
annotation module:
module com.foo.annotation {
exports com.foo.annotation;
}
annotation.processor module:
module com.foo.annotation.processors {
requires com.foo.annotation;
requires java.compiler;
}
client module:
module com.foo.client {
exports com.foo.client;
requires com.foo.annotation;
requires java.compiler;
}
Why? Because we add
@Generated annotation
annotation
annotation.processor
client
ANNOTATION PROCESSORS AND MODULES
Copyright © 2017 Accenture. All rights reserved. 33
Creating classes in modules
DEMO
https://github.com/restalion/deors.demos.annotations/tree/jdk9
Copyright © 2017 Accenture. All rights reserved. 34
• APT API is as powerful as in previous versions.
• All your legacy code still works as expected.
• You can add a couple a of new functionalities:
• @Generator annotation
• Simplified processing of multiple annotations
• You can also manage file generation in other modules
SUMMARY
Q & A
Copyright © 2017 Accenture. All rights reserved. 35
Many thanks for attending!
@_deors
https://github.com/deors
@restalion
https://github.com/restalion

More Related Content

What's hot

What's hot (20)

NATS for Modern Messaging and Microservices
NATS for Modern Messaging and MicroservicesNATS for Modern Messaging and Microservices
NATS for Modern Messaging and Microservices
 
Apache Kafka as Message Queue for your microservices and other occasions
Apache Kafka as Message Queue for your microservices and other occasionsApache Kafka as Message Queue for your microservices and other occasions
Apache Kafka as Message Queue for your microservices and other occasions
 
Removing performance bottlenecks with Kafka Monitoring and topic configuration
Removing performance bottlenecks with Kafka Monitoring and topic configurationRemoving performance bottlenecks with Kafka Monitoring and topic configuration
Removing performance bottlenecks with Kafka Monitoring and topic configuration
 
Swagger / Quick Start Guide
Swagger / Quick Start GuideSwagger / Quick Start Guide
Swagger / Quick Start Guide
 
Secure your app with keycloak
Secure your app with keycloakSecure your app with keycloak
Secure your app with keycloak
 
Json web token
Json web tokenJson web token
Json web token
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Building Microservices with Apache Kafka
Building Microservices with Apache KafkaBuilding Microservices with Apache Kafka
Building Microservices with Apache Kafka
 
From a monolith to microservices + REST: The evolution of LinkedIn's architec...
From a monolith to microservices + REST: The evolution of LinkedIn's architec...From a monolith to microservices + REST: The evolution of LinkedIn's architec...
From a monolith to microservices + REST: The evolution of LinkedIn's architec...
 
InnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick FiguresInnoDB Locking Explained with Stick Figures
InnoDB Locking Explained with Stick Figures
 
RESTful API Design, Second Edition
RESTful API Design, Second EditionRESTful API Design, Second Edition
RESTful API Design, Second Edition
 
Keycloak Single Sign-On
Keycloak Single Sign-OnKeycloak Single Sign-On
Keycloak Single Sign-On
 
OPA open policy agent
OPA open policy agentOPA open policy agent
OPA open policy agent
 
[215]네이버콘텐츠통계서비스소개 김기영
[215]네이버콘텐츠통계서비스소개 김기영[215]네이버콘텐츠통계서비스소개 김기영
[215]네이버콘텐츠통계서비스소개 김기영
 
Kafka basics
Kafka basicsKafka basics
Kafka basics
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresPerformance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and Underscores
 
Practical Design Patterns in Docker Networking
Practical Design Patterns in Docker NetworkingPractical Design Patterns in Docker Networking
Practical Design Patterns in Docker Networking
 
Tutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPTutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHP
 

Similar to JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of the Art in Java 9

UKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basicsUKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basics
Ulrich Krause
 
Ankit Chohan - Java
Ankit Chohan - JavaAnkit Chohan - Java
Ankit Chohan - Java
Ankit Chohan
 
Java ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many LanguagesJava ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many Languages
elliando dias
 

Similar to JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of the Art in Java 9 (20)

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...
 
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!
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
 
Gwt and JSR 269's Pluggable Annotation Processing API
Gwt and JSR 269's Pluggable Annotation Processing APIGwt and JSR 269's Pluggable Annotation Processing API
Gwt and JSR 269's Pluggable Annotation Processing API
 
Eclipse e4
Eclipse e4Eclipse e4
Eclipse e4
 
Infinum Android Talks #02 - How to write an annotation processor in Android
Infinum Android Talks #02 - How to write an annotation processor in AndroidInfinum Android Talks #02 - How to write an annotation processor in Android
Infinum Android Talks #02 - How to write an annotation processor in Android
 
Intro to Perfect - LA presentation
Intro to Perfect - LA presentationIntro to Perfect - LA presentation
Intro to Perfect - LA presentation
 
UKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basicsUKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basics
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
 
2. introduction to compiler
2. introduction to compiler2. introduction to compiler
2. introduction to compiler
 
Ankit Chohan - Java
Ankit Chohan - JavaAnkit Chohan - Java
Ankit Chohan - Java
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
Why Drupal is Rockstar?
Why Drupal is Rockstar?Why Drupal is Rockstar?
Why Drupal is Rockstar?
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
[DanNotes] XPages - Beyound the Basics
[DanNotes] XPages - Beyound the Basics[DanNotes] XPages - Beyound the Basics
[DanNotes] XPages - Beyound the Basics
 
Introduction to webprogramming using PHP and MySQL
Introduction to webprogramming using PHP and MySQLIntroduction to webprogramming using PHP and MySQL
Introduction to webprogramming using PHP and MySQL
 
Java se7 features
Java se7 featuresJava se7 features
Java se7 features
 
Java ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many LanguagesJava ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many Languages
 

More from Jorge Hidalgo

More from Jorge Hidalgo (20)

GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22
 
GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18GraalVM - OpenSlava 2019-10-18
GraalVM - OpenSlava 2019-10-18
 
Architecture 2020 - eComputing 2019-07-01
Architecture 2020 - eComputing 2019-07-01Architecture 2020 - eComputing 2019-07-01
Architecture 2020 - eComputing 2019-07-01
 
GraalVM - JBCNConf 2019-05-28
GraalVM - JBCNConf 2019-05-28GraalVM - JBCNConf 2019-05-28
GraalVM - JBCNConf 2019-05-28
 
GraalVM - MálagaJUG 2018-11-29
GraalVM - MálagaJUG 2018-11-29GraalVM - MálagaJUG 2018-11-29
GraalVM - MálagaJUG 2018-11-29
 
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Commit Conf 2018)
 
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...
Multilanguage Pipelines with Jenkins, Docker and Kubernetes (Oracle Code One ...
 
Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...
Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...
Multilanguage pipelines with Jenkins, Docker and Kubernetes (DevOpsDays Riga ...
 
DevOps Te Cambia la Vida - eComputing 2018-07-03
DevOps Te Cambia la Vida - eComputing 2018-07-03DevOps Te Cambia la Vida - eComputing 2018-07-03
DevOps Te Cambia la Vida - eComputing 2018-07-03
 
Open Source Power Tools - Opensouthcode 2018-06-02
Open Source Power Tools - Opensouthcode 2018-06-02Open Source Power Tools - Opensouthcode 2018-06-02
Open Source Power Tools - Opensouthcode 2018-06-02
 
JavaOne 2017 CON3276 - Selenium Testing Patterns Reloaded
JavaOne 2017 CON3276 - Selenium Testing Patterns ReloadedJavaOne 2017 CON3276 - Selenium Testing Patterns Reloaded
JavaOne 2017 CON3276 - Selenium Testing Patterns Reloaded
 
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power ToolsJavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
 
All Your Faces Belong to Us - Opensouthcode 2017-05-06
All Your Faces Belong to Us - Opensouthcode 2017-05-06All Your Faces Belong to Us - Opensouthcode 2017-05-06
All Your Faces Belong to Us - Opensouthcode 2017-05-06
 
Por qué DevOps, por qué ahora @ CHAPI 2017
Por qué DevOps, por qué ahora @ CHAPI 2017Por qué DevOps, por qué ahora @ CHAPI 2017
Por qué DevOps, por qué ahora @ CHAPI 2017
 
Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)
Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)
Accenture Liquid Architectures (for Master EMSE UPM-FI - April 2017)
 
La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17
La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17
La JVM y el Internet de las Cosas @ MálagaJUG 2016-11-17
 
OpenSlava 2016 - Lightweight Java Architectures
OpenSlava 2016 - Lightweight Java ArchitecturesOpenSlava 2016 - Lightweight Java Architectures
OpenSlava 2016 - Lightweight Java Architectures
 
JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook
JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A CookbookJavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook
JavaOne 2016 - CON3080 - Testing Java Web Applications with Selenium: A Cookbook
 
OpenSouthCode 2016 - Accenture DevOps Platform 2016-05-07
OpenSouthCode 2016  - Accenture DevOps Platform 2016-05-07OpenSouthCode 2016  - Accenture DevOps Platform 2016-05-07
OpenSouthCode 2016 - Accenture DevOps Platform 2016-05-07
 
JavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost Computers
JavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost ComputersJavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost Computers
JavaOne 2015 - CON6489 - Smart Open Spaces Powered by Low Cost Computers
 

Recently uploaded

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
+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
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Recently uploaded (20)

Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
+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...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 

JavaOne 2017 CON3282 - Code Generation with Annotation Processors: State of the Art in Java 9

  • 1. CODE GENERATION WITH ANNOTATION PROCESSORS: STATE OF THE ART IN JAVA 9 [CON3282]
  • 2. ABOUT THE SPEAKERS Copyright © 2017 Accenture. All rights reserved. 2 Welcome to our session! Julio Palma Vázquez Member – Málaga JUG Technology Architect – Accenture Technology Accenture Global Java Champion Accenture Delivery Center in Spain Mountain biker, AD&D player, Sid Meier’s Civilization gamer, LotR fan, … @restalion https://github.com/restalion Jorge Hidalgo Coordinator – Málaga JUG Global Java Lead – Accenture Technology Java, Architecture & DevOps Lead Accenture Delivery Center in Spain Father of two children, husband, whistle player, video gamer, sci- fi ‘junkie’, Star Wars ‘addict’, Lego brick ‘wielder’, Raspberry Pi fan, … LLAP! @_deors https://github.com/deors
  • 3. • Overview of Annotations and Annotation Processors in Java • What’s new in Java 9 APT API • Learn how to create Annotation Processors • Learn how to use Annotation Processors to generate source code • Annotation Processors and Modules in Java 9 • With lots of examples and source code CODE GENERATION IN THE JAVA COMPILER Copyright © 2017 Accenture. All rights reserved. 3 Objetives for the session
  • 4. Please raise your hands if you are familiar with Annotations, know how to use them or are even capable of writing Annotation Types POLL #1 Copyright © 2017 Accenture. All rights reserved. 4
  • 5. ANNOTATIONS IN JAVA LANGUAGE Copyright © 2017 Accenture. All rights reserved. 5
  • 6. • Annotations were first introduced in Java 5 • Add metadata capabilities to the Java language: • Build/deployment information • Configuration properties • Compiler behavior • Quality checks • Dependency injection • Persistence mapping • ... ANNOTATIONS IN THE JAVA LANGUAGE Copyright © 2017 Accenture. All rights reserved. 6 History
  • 7. • Annotations always appear before the annotated piece of code • Annotations can ‘decorate’... • Packages • Types (classes, interfaces, enums, annotation types) • Variables (class, instance and local variables) • Constructors, methods and their parameters • Generic type parameter (since Java 8) • Any type use (since Java 8) ANNOTATIONS IN THE JAVA LANGUAGE Copyright © 2017 Accenture. All rights reserved. 7 Overview
  • 8. • Can be grouped, nested, repeated... very powerful! Map<@NonNull String, @NonEmpty List<@Readonly Document>> docStore; • Annotations may be used just as a ‘marker’ @NonNull String email; • They may contain name-value pairs, and arrays @Author(name = "Albert", created = "17/09/2010", revision = 3, reviewers = {"George", "Fred"}) public class SomeClass {...} • Can be defined with default values, and then omitted when used • When it has only one attribute named value, it can be omitted, too @DatabaseTable(“MY_TABLE”) public class MyTable {...} ANNOTATIONS IN THE JAVA LANGUAGE Copyright © 2017 Accenture. All rights reserved. 8 Overview
  • 9. HOW TO CREATE ANNOTATIONS AND ANNOTATION PROCESSORS Copyright © 2017 Accenture. All rights reserved. 9
  • 10. Please raise your hands if you are familiar with Annotation Processors, their capabilities or know how to write new ones POLL #2 Copyright © 2017 Accenture. All rights reserved. 10
  • 11. • A special type of interface public @interface Author { String name(); String created(); int revision() default 1; String[] reviewers() default {}; } • Only primitives, enum types, annotation types, String, Class and arrays of them are allowed as elements • May be annotated itself, i.e. to define the retention policy or targets @Retention(RetentionPolicy.SOURCE) @Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE}) public @interface Author {...} Can trigger custom actions at compile time managed by Annotation Processors! ANNOTATIONS Copyright © 2017 Accenture. All rights reserved. 11 Create an Annotation Type
  • 12. • Annotation Processor: – Implements javax.annotation.processing.Processor – Or extends javax.annotation.processing.AbstractProcessor • May use three annotations to configure itself: – jx.a.p.SupportedAnnotationTypes – Used to flag which Annotation Types are managed by the – jx.a.p.SupportedSourceVersion – Used to flag the latest Java source level supported by the processor – jx.a.p.SupportedOptions – Used to register custom parameters that may be passed through the • TL;DR – Implement the process() method ANNOTATION PROCESSORS Copyright © 2017 Accenture. All rights reserved. 12 Annotation Processing API
  • 13. • Annotation processing happens in ‘rounds’ • In each round, a subset of sources are compiled, and then processors matching the annotations found on those sources are called • Processing ends when no more sources/annotations are pending • Processors may claim all annotation types with a wildcard • process() method has two parameters: – Set<? extends jx.lang.model.element.TypeElement> – subset of annotations being processed – jx.a.p.RoundEnvironment – access to information about the current and previous round ANNOTATION PROCESSORS Copyright © 2017 Accenture. All rights reserved. 13 Annotation Processing API
  • 14. jx.a.p.ProcessingEnvironment also provides access to the Filer utility that allows for easy file creation • Files are placed in the right folder as required by the compiler settings • Folder hierarchy matching the package name JavaFileObject jfo = processingEnv.getFiler() .createSourceFile(newClassQualifiedName); Writer writer = jfo.openWriter(); ...or... JavaFileObject jfo = processingEnv.getFiler() .createClassFile(newClassQualifiedName); OutputStream os = jfo.openOutputStream(); ANNOTATION PROCESSORS Copyright © 2017 Accenture. All rights reserved. 14 Creating Files
  • 15. Annotation Processors leverage the standard services mechanism • Package the processors in a Jar file • Include file META-INF/services/javax.annotation.processing.Processor • Contents are the fully qualified names of the bundled processors, one per line ANNOTATION PROCESSORS Copyright © 2017 Accenture. All rights reserved. 15 How the compiler knows?
  • 16. Find more information about APT in JavaOne 2014 session: https://www.slideshare.net/deors/javaone-2014-con2013-code-generation-in-the-java-compiler-annotation-processors-do-the-hard-work https://www.youtube.com/watch?v=xswPPwYPAFM ANNOTATION PROCESSORS Copyright © 2017 Accenture. All rights reserved. 16 Running Annotation Processors
  • 17. Multiple ways: • javac • Apache Maven builds • Continuous Integration builds • IDE ANNOTATION PROCESSORS Copyright © 2017 Accenture. All rights reserved. 17 Running Annotation Processors
  • 18. ADAPT LEGACY APT PROJECTS TO JAVA 9 Copyright © 2017 Accenture. All rights reserved. 18
  • 19. • Update <java.version> tag in pom.xml <java.version>1.9</java.version> • Update version of maven-compiler-plugin <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.2</version> • Upgrade the supported source version in Processor class @SupportedAnnotationTypes(“com.foo.AnnotationSample") @SupportedSourceVersion(SourceVersion.RELEASE_9) public class AnnotationSampleProcessor ADAPT LEGACY CODE Copyright © 2017 Accenture. All rights reserved. 19 Upgrading your code to Java 9
  • 20. • mvn clean install finish without errors: ANNOTATIONS API IN JAVA 9 Copyright © 2017 Accenture. All rights reserved. 20 Upgrading your code to Java 9
  • 21. DEMO ANNOTATIONS API IN JAVA 9 Copyright © 2017 Accenture. All rights reserved. 21 Executing upgraded projects
  • 22. Upgraded legacy code sample can be found in github: https://github.com/deors/deors.demos.annotations ADAPT LEGACY CODE Copyright © 2017 Accenture. All rights reserved. 22 Upgrading your code to Java 9
  • 23. WHAT’S NEW IN JAVA 9 APT API Copyright © 2017 Accenture. All rights reserved. 23
  • 24. ANNOTATIONS API IN JAVA 9 Copyright © 2017 Accenture. All rights reserved. 24 Overview • New @Generated Annotation • To add information about the annotation processor, date, and comments: @Generated(value = "com.foo.processors.SampleProcessor", date = "2017-09-28T09:43:28.170886", comments = "Sample") • Processed as a subsequent step by the annotation processor. • Two new methods in RoundEnvironment interface • Simplify processing of multiple annotations default Set<? extends Element> getElementsAnnotatedWithAny​( Set<Class<? extends Annotation>> annotations); default Set<? extends Element> getElementsAnnotatedWithAny​( TypeElement... annotations);
  • 25. ANNOTATIONS API IN JAVA 9 Copyright © 2017 Accenture. All rights reserved. 25 Overview • Changes in all methods of Filer interface. To manage files in a module, module name is prefixed to the type name and separated using a “/” character, i.e.: JavaFileObject jfo = processingEnv.getFiler().createSourceFile( "com.foo/com.foo.Bar"); JavaFileObject jfo = processingEnv.getFiler().getResource(location, "com.foo/com.foo", "Bar");
  • 26. NEW FEATURES IN JAVA 9 Copyright © 2017 Accenture. All rights reserved. 26 • It’s a best practice to include this annotation in the generated code: bw.append("@Generated(value = "" + this.getClass().getName() + "" , date = "" + LocalDateTime.now() + "", comments = "Test generator")"); Generated Annotation Comments MUST have the name of the code generator Date when the source was generated
  • 27. • During annotation processing,the Generated annotation will be found but nothing is done, it’s just informational. • Generated code: NEW FEATURES IN JAVA 9 Copyright © 2017 Accenture. All rights reserved. 27 Generated Annotation Name of the code generator Generation date Comments
  • 28. ANNOTATIONS API IN JAVA 9 Copyright © 2017 Accenture. All rights reserved. 28 Module
  • 29. ANNOTATION PROCESSORS AND MODULES IN JAVA 9 Copyright © 2017 Accenture. All rights reserved. 29
  • 30. ANNOTATION PROCESSORS AND MODULES Copyright © 2017 Accenture. All rights reserved. 30 Creating classes in modules • In previous examples we have three different jar files: • Annotation type • Annotation processor • classes that use annotations • Dependencies are managed using the regular classpath 30 annotation annotation.processor client
  • 31. ANNOTATION PROCESSORS AND MODULES Copyright © 2017 Accenture. All rights reserved. 31 Grouping classes in modules • One module per jar file. • Put a module-info.java file into each module. • Each module-info file needs to define exported packages and required modules. annotation annotation.processor client
  • 32. ANNOTATION PROCESSORS AND MODULES Copyright © 2017 Accenture. All rights reserved. 32 Creating classes in modules annotation module: module com.foo.annotation { exports com.foo.annotation; } annotation.processor module: module com.foo.annotation.processors { requires com.foo.annotation; requires java.compiler; } client module: module com.foo.client { exports com.foo.client; requires com.foo.annotation; requires java.compiler; } Why? Because we add @Generated annotation annotation annotation.processor client
  • 33. ANNOTATION PROCESSORS AND MODULES Copyright © 2017 Accenture. All rights reserved. 33 Creating classes in modules DEMO https://github.com/restalion/deors.demos.annotations/tree/jdk9
  • 34. Copyright © 2017 Accenture. All rights reserved. 34 • APT API is as powerful as in previous versions. • All your legacy code still works as expected. • You can add a couple a of new functionalities: • @Generator annotation • Simplified processing of multiple annotations • You can also manage file generation in other modules SUMMARY
  • 35. Q & A Copyright © 2017 Accenture. All rights reserved. 35 Many thanks for attending! @_deors https://github.com/deors @restalion https://github.com/restalion