AlikElzin-kilaka
AlikElzin-kilaka

Reputation: 36021

Java: prevent using high version APIs when compiling using a high version JDK but running on a low version JRE

I'm gradually migrating a project at work from Java 7 to 8.

I'd like to do this in 2 steps - migrate the build machines and then the run-time machines.

BUT

even though the compiler args are set to source=7 and target=7, it seems that when using JAVA 8 APIs, like streams and Optional, the compilation still passes successfully. Obviously, the code will break by a ClassNotFoundException when it will be executed on a Java 7 machine.

This is very surprising. How can I protect against using high version APIs when running on the correctly specified low version JRE?

Upvotes: 2

Views: 54

Answers (1)

AlikElzin-kilaka
AlikElzin-kilaka

Reputation: 36021

Found a way, using the bootclasspath feature.

In the build machine, though the build is done by a Java 8 compiler, I'm specifying the -bootclasspath param, providing a Java 7 rt.jar.

Example(raw):

javac <all-other-params> -bootclasspath /usr/alik/jdk1.7.0_21-rt.jar

Maven example:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
        <source>7</source>
        <target>7</target>
        <compilerArguments>
            <bootclasspath>/usr/alik/jdk1.7.0_21-rt.jar</bootclasspath>
        </compilerArguments>
    </configuration>
</plugin>

When a developer is trying to use a Java 8 API, like Optional, the compilation finally fails with the error: cannot find symbol class Optional.

Upvotes: 3

Related Questions