Skip to content

Instantly share code, notes, and snippets.

@aslakknutsen
Last active October 2, 2024 15:10
Show Gist options
  • Save aslakknutsen/9648594 to your computer and use it in GitHub Desktop.
Save aslakknutsen/9648594 to your computer and use it in GitHub Desktop.
Example of how to use both JDK 7 and JDK 8 in one build.

JDK 8 Released

Most of us won’t be able to use/deploy JDK 8 in production for a looong time. But that shouldn’t stop us from using it, right?

It should be possible to sneak in JDK 8 in the back way, the same way we snuck in Groovy and other libraries we wanted to use.

The Test Suite to the rescue

The Maven compiler plugin run in two separate lifecycles, compile and testCompile. Those can be configured separately.

The Maven Compiler even comes with support out of the box to separate them.

If you’re lucky and don’t have some elaborate parent pom setup that sets up most of the plugins for you, the only thing you need to do is add the following to your pom:

   <properties>
      <maven.compiler.target>1.7</maven.compiler.target>
      <maven.compiler.source>1.7</maven.compiler.source>
      <maven.compiler.testTarget>1.8</maven.compiler.testTarget>
      <maven.compiler.testSource>1.8</maven.compiler.testSource>
   </properties>

Now your src/main/java is compiled with target 1.7, and src/main/test compiled with target 1.8.

If you happen to have a parent pom that dominates your world, you might have to override the configuration a bit deeper. Something similar to this should work:

   <build>
      <plugins>
...
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <executions>
               <execution>
                  <id>default-compile</id>
                  <configuration>
                     <showDeprecation>true</showDeprecation>
                     <showWarnings>true</showWarnings>
                     <compilerArguments>
                        <source>${maven.compiler.target}</source>
                        <target>${maven.compiler.source}</target>
                     </compilerArguments>
                  </configuration>
               </execution>
               <execution>
                  <id>default-testCompile</id>
                  <configuration>
                     <showDeprecation>true</showDeprecation>
                     <showWarnings>true</showWarnings>
                     <compilerArguments>
                        <source>${maven.compiler.testTarget}</source>
                        <target>${maven.compiler.testSource}</target>
                     </compilerArguments>
                  </configuration>
               </execution>
            </executions>
         </plugin>
...
      </plugins>
   </build>

To be able to test your project you’re now forced to use JDK 8. We probably want to tell the other developers that by enforcing the same level as our tests.

Under the build section add:

         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-enforcer-plugin</artifactId>
            <version>1.3.1</version>
            <executions>
               <execution>
                  <id>enforce-java</id>
                  <goals>
                     <goal>enforce</goal>
                  </goals>
                  <configuration>
                     <rules>
                        <requireJavaVersion>
                           <version>${maven.compiler.testTarget}</version>
                        </requireJavaVersion>
                     </rules>
                  </configuration>
               </execution>
            </executions>
         </plugin>

With that mind, even tho we compile with target 1.7, the compiler doesn’t know the difference between the API’s available in 1.7 and 1.8. Which means it will still compile just fine if your src/main/java classes contain calls to APIs new in 1.8. We would want to avoid JDK 8 sneaking into production, so we need to setup a API verifier that fail the build if non 1.7 API’s are found by adding this to our build section:

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

With the project setup, we can now enjoy JDK 8 in our test suite.

Our boring JDK 1.7 source:

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;

public class DoSomething {

   public String execute(Callable<String> call) throws Exception {
      return call.call();
   }

   public List<String> list() {
      return Arrays.asList("a", "b", "c", "d");
   }
}

And the cool new JDK 8 enabled Test Suite:

import java.util.Optional;

import org.junit.Assert;
import org.junit.Test;

public class DoSomethingTestClase {

   public static final String TEST = "ABCD";

   @Test
   public void shouldReturnString() throws Exception {

      String result = new DoSomething().execute(()-> TEST);

      Assert.assertEquals(TEST, result);
   }

   @Test
   public void shouldFilterResult() throws Exception {

      Optional<String> result = new DoSomething().list()
         .stream()
            .map((a)-> a.toUpperCase())
            .reduce((a, b)->a+b);

      Assert.assertTrue(result.isPresent());
      Assert.assertEquals(TEST, result.get());
   }
}

Enjoy!

@jotomo
Copy link

jotomo commented Oct 5, 2015

@jhalterman I'm using the following solution/workaround:
Add this to your (parent) POM:

    <profiles>
        <profile>
            <id>ide</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.1</version>
                        <configuration>
                            <source>${maven.compiler.testSource}</source>
                            <target>${maven.compiler.testTarget}</target>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

This profile sets Java language level 8 for all code. In Eclipse, open project settings and in the Maven section add ide as an active Maven profile.
Intellij has a Maven tool window under which the ide profile can be activated (Intellij has the same issue as Eclipse, only recognises the 1.7 source directive).
It is a workaround because the IDEs now treat all code as Java 8 code but Maven builds will still fail correctly should any Java 8 code accidentially sneak into production sources. HTH.

@tan9
Copy link

tan9 commented Feb 7, 2017

You can dependent on IDE-specific properties to auto activate profile for development as following:

    <profiles>
        <profile>
            <id>development-in-eclipse</id>
            <activation>
                <property>
                    <name>m2e.version</name>
                </property>
            </activation>
            <properties>
                <maven.compiler.target>1.8</maven.compiler.target>
                <maven.compiler.source>1.8</maven.compiler.source>
            </properties>
        </profile>
        <profile>
            <id>development-in-idea</id>
            <activation>
                <property>
                    <name>idea.version</name>
                </property>
            </activation>
            <properties>
                <maven.compiler.target>1.8</maven.compiler.target>
                <maven.compiler.source>1.8</maven.compiler.source>
            </properties>
        </profile>
    </profiles>

@serkanaslan2k
Copy link

At the same time this change is solution for "No JUnit tests found' in Eclipse". error.

instead of this code "maven.compiler.target>1.7</maven.compiler.target"

paste

"maven.compiler.target>1.8</maven.compiler.target"

it worked for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment