1. Overview
This quick tutorial introduces the compiler plugin, one of the core plugins of the Maven build tool.
For an overview of the other core plugins, refer to this article.
2. Plugin Goals
The compiler plugin is used to compile the source code of a Maven project. This plugin has two goals, which are already bound to specific phases of the default lifecycle:
- compile – compile main source files
- testCompile – compile test source files
Here’s the compiler plugin in the POM:
<plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> ... </configuration> </plugin>
We can find the latest version of this plugin here.
3. Configuration
By default, the compiler plugin compiles source code compatible with Java 5, and the generated classes also work with Java 5 regardless of the JDK in use. We can modify these settings in the configuration element:
<configuration> <source>1.8</source> <target>1.8</target> <-- other customizations --> </configuration>
For convenience, we can set the Java version as properties of the POM:
<properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties>
Sometimes we want to pass arguments to the javac compiler. This is where the compilerArgs parameter comes in handy.
For instance, we can specify the following configuration for the compiler to warn about unchecked operations:
<configuration> <!-- other configuration --> <compilerArgs> <arg>-Xlint:unchecked</arg> </compilerArgs> </configuration>
When compiling this class:
public class Data { List<String> textList = new ArrayList(); public void addText(String text) { textList.add(text); } public List getTextList() { return this.textList; } }
we’ll see an unchecked warning on the console:
[WARNING] ... Data.java:[7,29] unchecked conversion required: java.util.List<java.lang.String> found: java.util.ArrayList
As both goals of the compiler plugin are automatically bound to phases in the Maven default lifecycle, we can execute these goals with the commands mvn compile and mvn test-compile.
4. Conclusion
In this article, we went over the compiler plugin and described how to use it.
The complete source code for this tutorial can be found over on GitHub.