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)
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.