enp4yne
enp4yne

Reputation: 646

maven ignores sourcelevel in pom.xml

Okay, I'm pretty sure I'm missing a fundamental point here, but I'm stumped. I'm playing around with maven to get main and test sources to compile at different levels (1.7 & 1.8) - found a lot of posts but haven't gotten it working yet, so back to basics with an empty project.

So first, I want to try off by having maven not compile my code by setting the maven-compiler-plugin to source level 1.7 and using 1.8 code (stream).

This is my test code:

public static void main(String[] args) {
    new ArrayList<>().stream();
}

And this is my pom.xml:

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

IntellIJ is not having any of it and complains about the source level as expected until I change it. Now, why is it that when running maven from the command line...

$ mvn compile

or

$ mvn install

Maven won't complain?

maven version 3.5.0
java version 1.8.0_131

Upvotes: 1

Views: 1196

Answers (1)

Mureinik
Mureinik

Reputation: 311308

There's nothing in the syntax that won't work in Java 7. However, the stream() method was only introduced in JDK 8. This code compiles because you happen to be using JDK 8. If you switch to an older JDK, your code will break.

One way to prevent such potential bugs is to use the Animal Sniffer Maven Plugin which allows you to check that you aren't using parts of the JDK that are too new, even when compiling against the aforementioned new JDK:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>animal-sniffer-maven-plugin</artifactId>
  <version>1.15</version>
  <configuration>
    <signature>
      <groupId>org.codehaus.mojo.signature</groupId>
      <artifactId>java17</artifactId>
      <version>1.0</version>
    </signature>
  </configuration>
  <executions>
    <execution>
      <id>animal-sniffer</id>
      <phase>compile</phase>
      <goals>
        <goal>check</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Upvotes: 1

Related Questions