java day 2016.pptx

18
CODE GENERATION WITH JAVAC PLUGIN

Upload: oleksandr-radchykov

Post on 16-Jan-2017

19 views

Category:

Engineering


0 download

TRANSCRIPT

Page 1: Java day 2016.pptx

CODE GENERATION WITH JAVAC PLUGIN

Page 2: Java day 2016.pptx

Hello!I am Oleksandr Radchykov

[email protected]

belict

Page 3: Java day 2016.pptx

Agenda

1. Motivation2. How to generate code?3. How to create plugin4. Demo

Page 4: Java day 2016.pptx

Motivation for code generation

Page 5: Java day 2016.pptx

Getting rid of boilerplate

class 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; }}

Page 6: Java day 2016.pptx

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

6

Page 7: Java day 2016.pptx

Getting rid from annoying code duplication

public String validate(Object input) { if (income instanceof String

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

Page 8: Java day 2016.pptx

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

8

Page 9: Java day 2016.pptx

Two ways to generate code

Page 10: Java day 2016.pptx

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

Page 11: Java day 2016.pptx

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

Page 12: Java day 2016.pptx

How to create javac plugin?

Page 13: Java day 2016.pptx

1. Implement Plugin interface

import com.sun.source.util.Plugin;

class MyPlugin implements Plugin { @Override public String getName() { return “pluginName”; }

@Override public void init(JavacTask javacTask,

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

Page 14: Java day 2016.pptx

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.

Page 15: Java day 2016.pptx

3. Compilation

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

Source.java

Page 16: Java day 2016.pptx

Demo

Page 17: Java day 2016.pptx

Questions?