Run SonarScanner analysis with Java 11, run target code with Java 8

Solution 1:

I'm not sure what is the problem. The announcements informs that you have to use Java 11+ to execute scans, but you can still compile your code with Java <11. You didn't provide any information about your project, so let's take a Maven project as an example.

It generally means that you have to do something like this:

// set Java to 8
export JAVA_HOME=/path/to/jdk8/

// compile, test and build
mvn package

// set Java to 11
export JAVA_HOME=/path/to/jdk11/

// execute scanner
mvn sonar:sonar

Solution 2:

While @agabrys offers the most straightforward solution and the one we use, albeit via Jenkins freestyle job, invoke maven top-level target package, then end-inject JAVA_HOME variable and invoke maven sonar step, an alternative approach is ...

Use Java 11 throughout, but in your maven pom, specify:

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

This is a minor risk of runtime incompatibility as noted at the bottom of that page.

Another alternative is to use profiles in conjunction with maven toolchains, tied to different profiles, one for the compilation and one for the analysis steps.