Gradle 6.7 introduced Java toolchains.
In the documentation, they state that Gradle chooses a JRE/JDK matching the requirements of the build ... By default, Gradle prefers installed JDKs over JREs... (from docs.gradle.org: Toolchains for JVM projects).
Thus, the JDK is chosen if we have both, JRE and JDK, installed.
Problem:
Imagine that the user only has a JRE installed.
Yet, we want to run our application via Gradle (JavaExec
task) using a Java toolchain, but have to ensure that a JDK is used for running because this application relies on tools.jar
, which is not part of a JRE.
Question:
Is it possible to force Gradle to use a JDK for all tasks (including running / launching), not just for compiling, when using a Java toolchain? (see following minimal example with comment)
// This build.gradle should ensure that the application is run using a JDK of version 9
plugins {
id 'application'
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(9)
// QUESTION: How to force JDK here? <------
}
}
// for JavaExec task runJar
tasks.withType(JavaExec).configureEach {
javaLauncher = javaToolchains.launcherFor(java.toolchain)
}
task runJar(type: JavaExec) {
classpath = files(jar.archiveFile)
}
...
The solution I finally came up with:
I now use org.gradle.java.installations.auto-detect=false
stored in a settings.gradle
file in my project. This ignores any locally installed Java versions when using Java toolchains in Gradle.
Thus, it will download a suitable JDK on the first run, and will reuse this JDK on future runs.
Upside: We ensure that even if a local JRE exists, we download a JDK (e.g., we can be sure that tools.jar
exists).
Downside: We also download a JDK if a matching one would exist on the machine.