Specifying the Java version for the Compiler plugin

When we created a new project in Eclipse, you would have observed the following warning:

Specifying the Java version for the Compiler plugin

Why does this error occur? This is because the Maven Compiler plugin, by default, considers the source and target Java version to be 1.5 (for backward compatibility reasons).

Let us resolve this warning.

How to do it...

Let us assume you have configured Java 8 as the default Java runtime in Eclipse, and perform the following steps:

  1. Open the Eclipse project.
  2. Add the following configuration to the Maven Compiler plugin:
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.2</version>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
            </configuration>
          </plugin>
        </plugins>
  3. Alternately, add the following properties in the properties element (this is essentially a shortcut for the earlier process):
    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>
  4. Check if the warning goes away.

How it works...

When the source and target versions of Java are explicitly set to the compiler, the version of java used in the source code as well as the desired version of the compiled classes are unambiguous. There is no likelihood of the compiler compiling to the incorrect target version of Java.

Consequently, the Eclipse warning goes away.

There's more...

You may need to pass compiler arguments in the compilerArguement element to the compiler. For instance, you may want to identify the usage of deprecated APIs in the code. You can do this by adding the following configuration:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.2</version>
    <configuration>
       <compilerArgument>-Xlint:deprecation</compilerArgument>
    </configuration>
</plugin>

When run on a code that has a deprecation, you can see the relevant lines:

[INFO] Compiling 1 source file to C:projectsapache-maven-cookbookproject-with-deprecation	argetclasses
[WARNING] /C:/projects/apache-maven-cookbook/project-with-deprecation/src/main/java/com/packt/cookbook/App.java:[12,24] Date(int,int,int) in java.util.Date has been deprecated
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.26.108