How do I specify the Java compiler version in a pom.xml file?

When you need to compile a project for a specific Java version you can configure maven compiler plugin to set the source and the target version. The following pom.xml file configuration show you how to do it.

<project>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>    

Invalid value for the source and the target version in our project will make our project compilation process failed. For example when we try to use the diamond operator (<>) which available in Java 7, while the maven compiler plugin is set to version 1.5, can produce compiler error like this:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project servlet-example: Compilation failure
[ERROR] /Users/wsaryada/Studio/kodejava.org/webapp-example/servlet-example/src/main/java/org/kodejava/example/servlet/SessionCounter.java:[10,51] diamond operator is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable diamond operator)

How do I programmatically compile Java class?

This example using the Java Compiler API introduced in JDK 1.6 to programmatically compile a Java class. Here we’ll compile the Hello.java. The process of compiling can be start by obtaining a JavaCompiler from the ToolProvider.getSystemJavaCompiler().

The simplest way to compile is by calling the run() method of the compiler and passing the first three arguments with null value. These three argument will use the default System.in, System.out and System.err. The final parameter is the file of the Java class to be compiled.

When error happened during compilation process the non-zero result code will be returned. After the compile process you’ll have the Hello.class just as if you were compiling using the javac command.

package org.kodejava.tools;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class CompileHello {
    public static void main(String[] args) {
        System.out.println(System.getProperty("user.dir"));
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int result = compiler.run(null, null, null,
                "kodejava-tools/src/main/java/org/kodejava/tools/Hello.java");

        System.out.println("Compile result code = " + result);
    }
}