45

Custom annotation processors for your production code

Embed Size (px)

Citation preview

Special mention to @jmpergar

Let’ s move on!

tooling

automatize as much as you can

why annotation processors?

1. From runtime to compile time

2. Avoid reflection

3. Eliminate boilerplate

Added in JDK 5

APT and Rich public API on JDK 6

Standardized through JSR 269

APT is a powerful tool

doable:

1. Scan sources for annotations

2. Generate source files

not doable:

1. Inject code into / modify sources

Reflective APIs:

1. Standard (Java Reflection API)

2. Mirror based ones (Java Mirror API)

ObjectMirror carMirror = Reflection.reflect(myCar);

before compiling, ServiceLoader runs

all the processors using source files

as input

¿how to register a processor?

Option 1:

static file declaring its path

include qualified name of your processor class

Option 2:

AutoService library

processing rounds

creating a custom processor

Extend AbstractProcessor and override some methods

get utility classes from processingEnvironment

4 phases per round

1. Scan for annotations

2. Static validation

3. Parse to meta-models

4. Code generation

1. Scan for annotations

get a Set of annotated Elements

1. Executable Element (method)

2. Type Element (class)

3. Variable Element (fields, method params)

2. Static Validation

get a Set of annotated Elements

3. Parse to meta-models

create meta-models to increase simplicity

4. Code generation

JavaPoet: Based on specs

https://github.com/square/javapoet

how to test to avoid compiling the whole project many times?

Truth + compile-testing

test validation code while developing it

test code generation

base classes to improve readability

debug is possible at compile time

1. divide your library in separate modules

(compiler, public api)

2. include other libraries just for compile time

(provided)

3. war plugin for pure java modules

public final recommendations {

● AutoService https://github.com/google/auto/tree/master/service

● Truth https://github.com/google/truth

● Compile-Testing https://github.com/google/compile-testing

● JavaPoet https://github.com/square/javapoet

● Great threads about creating your custom processor

http://hannesdorfmann.com/annotation-processing/annotationprocessing101

● https://deors.wordpress.com/2011/09/26/annotation-types/

https://deors.wordpress.com/2011/10/08/annotation-processors/

https://deors.wordpress.com/2011/10/31/annotation-generators/

● Some official (SUN) info about both types of reflective APIs http://bracha.org/mirrors.pdf

Resources and recommended reads

questions?