Explain Codes LogoExplain Codes Logo

How do I tell Gradle to use a specific JDK version?

java
gradle
jdk
build-configuration
Anton ShumikhinbyAnton Shumikhin·Sep 27, 2024
TLDR

Set Gradle to compile with a specific JDK version by introducing the java.toolchain into your build.gradle:

java.toolchain { languageVersion = JavaLanguageVersion.of(11) }

This instructs Gradle to compile with JDK 11, and it'll grab it automatically if it isn't available yet.

However, for a more granular control, or when you need to use a fixed JDK path, use the org.gradle.java.home property, and tweak it in your gradle.properties file or set it as an environment variable.

Setting JDK within the build.gradle

For scenarios where Gradle has to fork the compileJava task to employ a specific JDK version, manipulate the compileJava.options.fork and set a custom executable:

compileJava { options.fork = true options.forkOptions.executable = '/path/to/jdk/bin/javac' // FYI, javac: soldier of the Java army }

This directive informs Gradle to always bring into play the given javac for compilation, providing controlled access over which JDK version gets used.

Steer compatibility using source and target

To ensure your code is both compiled and run on a specific JDK version, maneuver sourceCompatibility and targetCompatibility:

sourceCompatibility = '11' targetCompatibility = '11' // These properties walk into a bar and...

This tells Gradle that the source code has to be compatible with JDK 11, and the compiled output should run flawlessly on a JVM which is compatible with JDK 11.

Compilation and runtime options in Gradle 7+

Starting from Gradle 7+, you can leverage options.release — corresponding to the --release compiler argument in JDK 9+. It's beneficial for ensuring precise binary compatibility at the time of compilation:

tasks.withType(JavaCompile) { options.release = 11 // James Bonded with release 11 }

This method scores over setting source and target compatibility. It assures comprehensive handling of API and code dependencies specific to the Java release.