Will
Will

Reputation: 915

Enforcing java 6 source compatibility in maven and/or eclipse

The method java.lang.Long.compare(x, y) exists in Java 7 but not Java 6. So obviously this causes a NoSuchMethodException if code using this method is deployed to a server running Java 6.

However, either Maven nor Eclipse were picking up the error despite having set the source-compliance level to 1.6 in eclipse and the maven compiler source & target to 1.6.

Is there a way to enforce full Java 6 compliance in Eclipse, apart from downgrading my JRE to 6?

Upvotes: 1

Views: 1799

Answers (3)

Robert Scholte
Robert Scholte

Reputation: 12335

This is exactly why the animalsniffer-maven-plugin was introduced:

Animal Sniffer provides tools to assist verifying that classes compiled with a newer JDK/API are compatible with an older JDK/API.

Upvotes: 4

Ben Thurley
Ben Thurley

Reputation: 7141

This is what I put in my POM.

<project    xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >


  ...

  <properties>
    <java-version>1.6</java-version>
  </properties>

  ...

  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>
            <configuration>
                <source>${java-version}</source>
                <target>${java-version}</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>

Once I have that defined in my POM I right click the project and go to Maven > Update project. This will apply any settings in the pom to the eclipse project which ensures the two are in sync.

In terms of JDK I use the latest JDK but compiled to the lower release. We're currently using JDK 7 but compile to 6. This gives you the best of both worlds in that the compiler will still make use of any optimizations that were introduced with 7 that are compatible with version 6.

Upvotes: 1

Puce
Puce

Reputation: 38122

There is a way to cross-compile Java source code, but the easiest way is to use the min. required JDK version when creating your artifacts (JARs etc.)/ during development.

-> use JDK 6 during development and releasing.

Note however that Oracle's JDK 6 reached End of Life and it is strongly recommended to upgrade to Java 7 if you don't have special support contracts with Oracle (or using a JDK from a different vendor).

Note: the source-level only makes sure you're using syntax constructs supported by that version and the target-level only makes sure the resulting class file is bytecode compliant to the specified version.

Upvotes: 0

Related Questions