Presentation is loading. Please wait.

Presentation is loading. Please wait.

Code Generation with Annotation Processors: State of the Art in Java 9

Similar presentations


Presentation on theme: "Code Generation with Annotation Processors: State of the Art in Java 9"— Presentation transcript:

1 Code Generation with Annotation Processors: State of the Art in Java 9
[CON3282]

2 About the speakers Welcome to our session! 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 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 Copyright © 2017 Accenture. All rights reserved.

3 Code Generation in the Java Compiler
Objetives for the session 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 Copyright © 2017 Accenture. All rights reserved.

4 Poll #1 Please raise your hands if you are familiar with Annotations, know how to use them or are even capable of writing Annotation Types Copyright © 2017 Accenture. All rights reserved.

5 Annotations in Java language
Copyright © 2017 Accenture. All rights reserved.

6 Annotations in the java language
History 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 ... Copyright © 2017 Accenture. All rights reserved.

7 Annotations in the java language
Overview 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) Copyright © 2017 Accenture. All rights reserved.

8 Annotations in the java language
Overview Can be grouped, nested, repeated... very powerful! Document>> docStore; Annotations may be used just as a ‘marker’ @NonNull String ; 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 {...} Copyright © 2017 Accenture. All rights reserved.

9 how to create Annotations and Annotation Processors
Copyright © 2017 Accenture. All rights reserved.

10 Poll #2 Please raise your hands if you are familiar with Annotation Processors, their capabilities or know how to write new ones Copyright © 2017 Accenture. All rights reserved.

11 Annotations Create an Annotation Type A special type of 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}) Author {...} Can trigger custom actions at compile time managed by Annotation Processors! Copyright © 2017 Accenture. All rights reserved.

12 Annotation Processors
Annotation Processing API 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 processor 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 command line TL;DR – Implement the process() method Copyright © 2017 Accenture. All rights reserved.

13 Annotation Processors
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 Copyright © 2017 Accenture. All rights reserved.

14 ANNOTATION PROCESSORS
Creating Files 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... .createClassFile(newClassQualifiedName); OutputStream os = jfo.openOutputStream(); Copyright © 2017 Accenture. All rights reserved.

15 ANNOTATION PROCESSORS
How the compiler knows? 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 Copyright © 2017 Accenture. All rights reserved.

16 Annotation Processors
Running Annotation Processors Find more information about APT in JavaOne 2014 session: annotation-processors-do-the-hard-work Copyright © 2017 Accenture. All rights reserved.

17 Annotation Processors
Running Annotation Processors Multiple ways: javac Apache Maven builds Continuous Integration builds IDE Copyright © 2017 Accenture. All rights reserved.

18 Adapt legacy APT projects to Java 9
Copyright © 2017 Accenture. All rights reserved.

19 Adapt legacy code Upgrading your code to Java 9
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 Copyright © 2017 Accenture. All rights reserved.

20 Annotations api in java 9
Upgrading your code to Java 9 mvn clean install finish without errors: Copyright © 2017 Accenture. All rights reserved.

21 Annotations api in java 9
Executing upgraded projects DEMO Copyright © 2017 Accenture. All rights reserved.

22 Adapt legacy code Upgrading your code to Java 9
Upgraded legacy code sample can be found in github: Copyright © 2017 Accenture. All rights reserved.

23 What’s new in Java 9 APT API
Copyright © 2017 Accenture. All rights reserved.

24 Annotations api in java 9
Overview Annotation To add information about the annotation processor, date, and comments: @Generated(value = "com.foo.processors.SampleProcessor", date = " T09:43: ", 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); TypeElement... annotations); Copyright © 2017 Accenture. All rights reserved.

25 Annotations api in java 9
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"); Copyright © 2017 Accenture. All rights reserved.

26 NEW features in java 9 Generated Annotation
It’s a best practice to include this annotation in the generated code: = \"" + this.getClass().getName() + "\" , date = \"" + LocalDateTime.now() + "\", comments = \"Test generator\")"); MUST have the name of the code generator Date when the source was generated Comments Copyright © 2017 Accenture. All rights reserved.

27 New features in java 9 Generated Annotation
During annotation processing,the Generated annotation will be found but nothing is done, it’s just informational. Generated code: Name of the code generator Generation date Comments Copyright © 2017 Accenture. All rights reserved.

28 Annotations api in java 9
Module Copyright © 2017 Accenture. All rights reserved.

29 Annotation Processors and Modules in Java 9
Copyright © 2017 Accenture. All rights reserved.

30 aNNOTATION PROCESSORS and modules
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 annotation.processor annotation client Copyright © 2017 Accenture. All rights reserved. 30

31 aNNOTATION PROCESSORS and modules
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.processor annotation client Copyright © 2017 Accenture. All rights reserved.

32 aNNOTATION PROCESSORS and modules
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; annotation.processor annotation client Why? Because we annotation Copyright © 2017 Accenture. All rights reserved.

33 aNNOTATION PROCESSORS and modules
Creating classes in modules DEMO Copyright © 2017 Accenture. All rights reserved.

34 SUMMARY 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 Copyright © 2017 Accenture. All rights reserved.

35 Q & A Many thanks for Copyright © 2017 Accenture. All rights reserved.


Download ppt "Code Generation with Annotation Processors: State of the Art in Java 9"

Similar presentations


Ads by Google