code generation with javac plugin

Post on 16-Jan-2017

424 Views

Category:

Engineering

5 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CODE GENERATION WITH JAVAC PLUGIN

Hello!I am Oleksandr Radchykov

committed.chinchilla@gmail.combelict

Motivation for code generation

Getting rid of boilerplateclass MyService { private final String name; private final Integer version;

public MyService(String name, Integer version) { this.name = name; this.version=version; }

public String getName() { return name; } public Integer getVersion() { return version; }}

@Getter@RequiredArgsConstructorclass MyService { private final String name; private final Integer version;}

Getting rid from annoying code duplicationpublic String validate(Object input) { if (income instanceof String

&& !((String) income).isEmpty()) { return (String) income; } …}

public String validate(Object input) { if (income instanceof String && !income.isEmpty()) { return income; } …}

Two ways to generate code

Annotation Processing

▷Java 5+▷Takes java code and generates source files

▷You can not manipulate an existing java code

▷Use the model of processing rounds

Javac Plugin

▷Since Java 8▷Can give us access to AST trees parsed from source code

▷Can be used to add compile-time checks

▷Can run on different phases of compilation process

How to create javac plugin?

1. Implement Plugin interfaceclass MyPlugin implements Plugin { @Override public String getName() { return “pluginName”; }

@Override public void init(JavacTask javacTask,

String… strings) { /*...*/ }}

2. Create provider-configuration file

MyPlugin.jar- com/example

- MyPlugin.class- META-INF/services

- com.sun.source.util.Plugin

Provider-configuration file should declare all plugins you want to expose.

3. Compilation

$ javac -Xplugin:PluginName \ –cp /path/to/plugin \

Source.java

Demo

Questions?

Thanks

committed.chinchilla@gmail.combelict

top related