How do I tell Gradle to use specific JDK version?

Solution 1:

Two ways

  1. In gradle.properties in the .gradle directory in your HOME_DIRECTORY set org.gradle.java.home=/path_to_jdk_directory

or:

  1. In your build.gradle

     compileJava.options.fork = true
     compileJava.options.forkOptions.executable = '/path_to_javac'
    

Solution 2:

If you add JDK_PATH in gradle.properties your build become dependent on on that particular path. Instead Run gradle task with following command line parametemer

gradle build -Dorg.gradle.java.home=/JDK_PATH

This way your build is not dependent on some concrete path.

Solution 3:

To people ending up here when searching for the Gradle equivalent of the Maven property maven.compiler.source (or <source>1.8</source>):

In build.gradle you can achieve this with

apply plugin: 'java'
sourceCompatibility = 1.8
targetCompatibility = 1.8

See the Gradle documentation on this.

Solution 4:

The right way to do this with modern versions of Gradle (version 6.7+) is to use the Gradle Java Toolchain support.

The following block, when the java plugin is applied to the current project, will use Java 11 in all java compilation, test, and javadoc tasks:

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

This can also be set for individual tasks.

NOTE: For other tasks relying on a Java executable or Java home, use the compiler metadata to set the appropriate options. Here is an example for the Kotlin compiler (though if you are using Kotlin 1.5.30+, don't use this method, see below instead):

val compiler = javaToolchains.compilerFor {
  languageVersion.set(JavaLanguageVersion.of(11))
}

tasks.withType<KotlinJvmCompile>().configureEach {
  kotlinOptions.jdkHome = compiler.get().metadata.installationPath.asFile.absolutePath
}

For Kotlin 1.5.30+, the Kotlin plugin supports toolchains directly:

kotlin {
  jvmToolchain {
    (this as JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of("11"))
  }
}

Solution 5:

If you have this problem from Intellij IDE, try this options

  1. Set Gradle JVM Home enter image description here

  2. Set the JDK version in the Project module settings enter image description here

  3. Check the JDK version in the Modules enter image description here