How do I tell Gradle to use specific JDK version?

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.

Gradle 7+

From Gradle 7 onwards, you can also use the release property, which makes use of the JDK 9 --release compiler argument:

tasks.withType(JavaCompile) {
    options.release = 8
}

(thanks Pedro Lamarão)


Gradle 6.7+ — Use Gradle Toolchain Support

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. See below for an example with the Kotlin plugin, prior to version 1.5.30.

Gradle attempts to auto-detect the location of the specified JDK via several common mechanisms. Custom locations can be configured if the auto-detection isn't sufficient.

Kotlin 1.5.30+

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

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

Kotlin Earlier Versions

Configuring the Kotlin compiler for versions prior to 1.5.30 involves using the toolchain API to determine the compiler, and passing that information to the plugin. Other compiler-based plugins may be configured in similar ways.

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

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

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.


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'