How do I tell Gradle to use a specific JDK version?
Set Gradle to compile with a specific JDK version by introducing the java.toolchain into your build.gradle:
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:
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:
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:
This method scores over setting source and target compatibility. It assures comprehensive handling of API and code dependencies specific to the Java release.
Was this article helpful?