520

I can't figure out to get this working.

Scenario:

  • I have an application built with gradle
  • The application uses JavaFX

What I want

  • Use a variable (defined per developer machine) which points to an installation of a JDK which will be used for building the whole application / tests / ...

I thought about having the gradle.properties file, defining the variable. Something like

JAVA_HOME_FOR_MY_PROJECT=<path to my desired JDK>

What I don't want

  • point JAVA_HOME to the desired JDK

I could live with many suggestions:

  • a solution that defines a system environment variable which I'm able to check in my build.gradle script
  • a variable defined in gradle.properties
  • overriding the JAVA_HOME variable only for the build context (something like use JAVA_HOME=<my special JDK path defined somewhere else defined>)
  • something else I didn't think about

Question:

  • How to wire a variable (how ever defined, as variable in the gradle.properties, system environment variable, ...) to the build process?

I have more than one JDK7 available and need to point to a special version (minimum JDK_u version).

Any answer is appreciated and I'm thankful for every hint to the right direction.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
bully
  • 5,525
  • 3
  • 22
  • 26
  • 7
    Have you tried setting `org.gradle.java.home` in the `gradle.properties` file? [link](http://www.gradle.org/docs/current/userguide/build_environment.html) – Ray Stojonic Aug 28 '13 at 12:38
  • in eclipse you can create "product config file" in to your project and you can pack the jdk with your product. No need to specify env variables. – mdanaci Aug 28 '13 at 13:01
  • 3
    @RayStojonic: I just gave it a try, but gradle still uses the JAVA_HOME JDK for building :( – bully Aug 28 '13 at 13:31
  • @mdanaci: I was really hoping I could avoid this because I honestly don't want to take a JDK under version control (which would be the consequence if I would use your suggestion) as any developer has to be able to pack the application. Plus, I see problems with the CI server this way. Thanks for your suggestion anyway :) – bully Aug 28 '13 at 13:35
  • 7
    As of a year ago, the `org.gradle.java.home` setting applies only to gradle daemon, apparently... At any rate, try setting fork to true and forkOptions.executable to the jdk you want to use: [link](http://forums.gradle.org/gradle/topics/setting_path_to_jdk) – Ray Stojonic Aug 28 '13 at 13:42
  • ah, too bad, I missed the link (though I found it on Google, but now I have a different sense for the content). Thanks, that did the trick, great :) – bully Aug 28 '13 at 13:58
  • Check http://stackoverflow.com/questions/22681544/how-to-set-gradle-options-bootclasspath-in-an-os-independent-manner - it is essentially the same question and it provides a way to run the gradle using one jdk and compile the project (or any module) using the other jdk. – Oleg Estekhin Apr 01 '14 at 06:12
  • To instead set the *source* and *target* SDK versions, see http://stackoverflow.com/a/19470405/712526. – jpaugh May 09 '16 at 23:29

23 Answers23

461

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'
    
Jesse Barnum
  • 6,507
  • 6
  • 40
  • 69
First Zero
  • 21,586
  • 6
  • 46
  • 45
  • 36
    The `gradle.properties` can be defined at project level too, see http://www.gradle.org/docs/current/userguide/build_environment.html – Paolo Fulgoni Jul 08 '14 at 10:32
  • 213
    If you are executing using gradle wrapper you can also do it like `./gradlew -Dorg.gradle.java.home=/path_to_jdk_directory`. Good if you don't want to touch `gradle.properties`. – david.schreiber May 20 '15 at 13:45
  • 67
    The question was how to set VERSION, not JDK PATH, wasn't it? – Dims Mar 05 '16 at 14:59
  • 5
    @Dims thats exactly how you do it, you have different versions of Java in different paths, then whichever version you want to use give that path. javac is a compiler(The program that actually compiles java code to byte code in the JDK), and its not hosted in Maven or Ivy repositories like how dependency libs are. – Bhargav Mar 10 '16 at 09:58
  • 78
    This way I can't share project with other developers, who have java in different paths. – Dims Mar 12 '16 at 07:06
  • 1
    How do I set the version much like in ant where if developers JAVA_HOME is 1.6, the build fails telling them version must be 1.8 and to change their JAVA_HOME. I don't want other developers be required to have the same JAVA_HOME path as me(or make them even be on the same OS)? – Dean Hiller Apr 17 '16 at 19:21
  • @Dims you can place in gradle.properties the path to java home, but it can be through a variable defined in a gradle-wraper.properties for example, this way you can export your project – bogdan.rusu Sep 18 '16 at 10:35
  • 19
    There's a difference between options 1 and 2 that should be clarified: In option 1 we are setting the JVM for gradle itself to run under which will also be used to run the compiler task (notice that javac itself is a java application), while in option 2 we are just setting javac to be spawned in its own JVM. If for whatever reason we need a specific JVM for gradle (e.g a given gradle plugin is compiled for say Java 8), then we would be forced to resort to forking a separate JVM for the compile process. – Basel Shishani Sep 29 '16 at 04:20
  • 1
    This is an interesting fix, but it could get interesting if you support building on more than one platform, and you also have different subprojects requiring different versions. It's a shame it can't be more declarative - you say which version you require, and per-system configuration takes care of saying where those actually are. Actually, it's a shame it can't just pull an artifact containing the JDK from the artifact server, so that when we bump the version of the JDK we depend on, people don't all have to go and manually download that version. – Hakanai Oct 11 '16 at 06:04
  • 1
    If you are using the gradle **wrapper**, you can use way 1 of @FirstZero : in your home path `\.gradle`, create a `gradle.properties` file, and add the line `org.gradle.java.home=/path_to_jdk_directory`. – Hugo P Feb 15 '18 at 17:05
  • 1
    Note that properties files use backslash escaping, so for a Windows-style path you'll need double backslashes. – Jules Apr 20 '18 at 19:33
  • in my case strange behaviour each time i rechange to JDK8 and try build it changes back to 7 , the solution was default JDK for IDE find here https://stackoverflow.com/questions/18987228/how-do-i-change-the-intellij-idea-default-jdk – shareef Jul 11 '18 at 11:46
  • 1
    just for anyone uses Mac OS and needs to know where it `path_to_jdk_directory`. In my case is will be found in `/Library/Java/JavaVirtualMachines/` folder. Example: `/Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk`. – Nezneika Sep 05 '19 at 10:01
  • 1
    If I use option 1 does it mean that if I run afterwards 'gradle -v' it would show me the previously set java version? I didn't observe it. It seems that gradle still uses the java set in JAVA_HOME and not in gradle.properties. Do I have to do some restart or refresh? I'm using linux. – ka3ak Dec 25 '19 at 20:07
  • I didn't had `gradle.properties` in my `~/.gradle` but I added one it is working fine. – Pierre Thibault Feb 27 '20 at 21:09
  • 2
    @Nezneika I'm also on a Mac and in my case I had to write `org.gradle.java.home=/Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home` – kuhr May 26 '20 at 14:18
  • 1
    You sir are a hero – Gabriel Garcia Apr 15 '21 at 10:04
  • Point 1 was how we got sorted, thank you so much! We upgraded our app to use Gradle 7 and part of that is running Java 11. For some reason despite our JAVA_HOME and -javac returning jdk11, this is how we got our builds to work! – kelvin Jan 25 '22 at 06:46
  • I don't see any jdk version or path in "build.gradle". My ".gradle" directory doesn't have any "gradle.properties". I'm using IntelliJ. – emeraldhieu Jun 06 '23 at 08:27
263

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.

mirmdasif
  • 6,014
  • 2
  • 22
  • 28
  • 4
    In Eclipse (Neon, 4.6) you can also set the Java Home within the Gradle build configuration (see tab "Java Home"). This is somewhat tedious work if you have 20+ build jobs... I think Gradle really needs to pick the Java Home directory from the system's configuration! – Markus L Jul 20 '16 at 12:39
  • 1
    This is a fair point. I have a soft-link called `/usr/lib/java/jdk/home` that points to the _current_ version installed. Of course when you want a specific version (e.g. u51) then you need to be specific about the path. Also some tools want to kick-off gradle don't seem to set the JDK in the environment they give gradle. And I for one never set the JDK as the current JAVA_HOME unless it is a development session. – will Aug 13 '16 at 13:46
  • 8
    Note that JDK_PATH can't have spaces on Windows, even if it's in quotes: you have change "Program Files" to `PROGRA~1` (all caps) or whatever else DIR /X tells you. – Noumenon Jan 23 '17 at 03:30
  • Not working for me. However, I'm using gradlew war (wrapper), maybe this is the cause? – TechFanDan Oct 10 '17 at 19:47
  • 2
    If you are using gradle wrapper invoke the command like this ./gradlew build -Dorg.gradle.java.home=/JDK_PATH Replace JDK_PATH with your jdk location in your environment like ' /opt/java/jdk1.7.0_79/bin/' – mirmdasif Oct 11 '17 at 07:19
  • @mirmdasif That's what I'm doing. However, since the default on the machine is Java6, it seems to want to use that instead of the path I specified. I'll keep on looking for solutions using this approach. – TechFanDan Oct 11 '17 at 11:48
  • 4
    `"... gradle itself (either standalone distribution or wrapper) uses JDK from JAVA_HOME environment variable or (if it is not set) from PATH".` I specified the JAVA_HOME prior to gradlew call to fix this. (ie. `env JAVA_HOME=/path/to/java gradlew war --stacktrace`) – TechFanDan Oct 11 '17 at 14:47
  • 1
    I've tried running this: ```.\gradlew.bat bootRun -Dorg.gradle.java.home="C:\Program Files\Java\jdk1.8.0_60" --info``` But am getting this error: ```Project '.gradle.java.home=C' not found in root project 'grails3-quick-start'.``` – Daniil Shevelev Mar 18 '18 at 16:36
  • You need to put 2 backslashes for paths in windows so run this .\gradlew.bat bootRun -Dorg.gradle.java.home="C:\\Program Files\\Java\\jdk1.8.0_60" – mirmdasif Mar 19 '18 at 06:23
  • 1
    On MacOS for Java 8: `-Dorg.gradle.java.home=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/` – Jonathan Komar Oct 26 '19 at 16:58
  • 1
    Example for JDK 8 on MacOSX to add the path dynamically: ./gradlew clean build -Dorg.gradle.java.home=`/usr/libexec/java_home -v 1.8` – Christoph Nov 20 '19 at 22:01
  • 1
    **WINDOWS** example: `.\gradlew test -D"org.gradle.java.home"="D:\jdk\jdk8oj9"` (mind the quotes) – acdcjunior Aug 31 '20 at 17:47
  • thanks. in 2022 i need to write `org.gradle.java.home=/JDK_PATH` inside the gradle.properties, removing the `gradle build -D` prefix from the answer – nashihu Mar 08 '22 at 06:24
  • My OS is Linux and I have my JAVA_HOME pointing to the correct path. I have even used this command `gradle build -Dorg.gradle.java.home=$JAVA_HOME` to prove my point. I've installed gradle using snap in Ubuntu and I'm guessing it is using some bundled JDK. – IamDOM May 22 '22 at 16:51
195

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)

Geert
  • 3,527
  • 1
  • 20
  • 16
  • 21
    @morgwai -- except that this *isn't* the answer to the question, which explicitly asks "What I want [is to set] a variable (defined per developer machine) which points to an installation of a JDK which will be used for building the whole application". The upvoted answers are correct; this answer is for an entirely different question. – Jules Apr 20 '18 at 19:19
  • 3
    This is ignored by tools such as the Javadoc task (which tries to generate the javadoc according to Java 9 with modules on my project that is specified to use Java 8) – CLOVIS Jul 05 '18 at 12:08
  • 7
    While not an exact answer for this question, this way actually works for more than just one system. Most people searching this question want to see this answer and not the other answers. – nathanfranke Sep 09 '20 at 03:46
  • 5
    I asked Google for "gradle specify jdk version" and it brought me here. The answer I was actually looking for is this one, regardless of what the question was actually about. Upvoted because useful. – Marko Topolnik Apr 18 '21 at 09:01
  • "except that this isn't the answer to the question", The question actually asks two questions... one is "specific JDK version?" (by title), the other is "an installation of a JDK" (by description). In my experience, the former is often more useful as newer JDKs can often target older JDK versions, allowing the existing location to achieve what the title (perhaps accidentally) asks. – tresf May 02 '22 at 19:47
  • 2
    For those coming in the future, Gradle's `JavaCompile` task now allows setting the `release` option. https://docs.gradle.org/current/dsl/org.gradle.api.tasks.compile.CompileOptions.html#org.gradle.api.tasks.compile.CompileOptions:release – Pedro Lamarão Aug 08 '22 at 14:06
100

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.7.20+

For Kotlin 1.7.20+, the Kotlin plugin supports toolchains directly and has a simplified syntax:

kotlin {
  jvmToolchain(17)
}

Kotlin 1.5.30+

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

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

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
}
Raman
  • 17,606
  • 5
  • 95
  • 112
  • Do i need to remove sourceCompatibility & targetCompatibility? Also if i want it to run with a specific java update, let's say Java 8 Update 281 instead of Java 8 Update 271, is it possible? – jumping_monkey Apr 15 '21 at 08:14
  • 2
    @jumping_monkey You can't define them at the `java { }` extension level, but you can still define them at the `JavaCompile` task level. Or use the new `release` flag on `CompileOptions`. See https://docs.gradle.org/current/userguide/building_java_projects.html#sec:java_cross_compilation. About the specific java update, see https://github.com/gradle/gradle/issues/16628. – Raman Apr 15 '21 at 13:20
  • 1
    how can i use the toolchain for all the plugins? cc @Raman – Sourav Jha Sep 17 '21 at 20:23
  • @SouravJha Depends on the plugin, but my answer describes how to use compiler metadata to set the appropriate options for your plugin(s). – Raman Sep 17 '21 at 20:38
  • 1
    I meant that for my project using Gradle as my build tool, I have the Gradle wrapper, on running the Gradle commands the plugins I have used, should use toolchain java instead of my machine's default java. Is there a global way to set compiler for all the plugins. – Sourav Jha Sep 18 '21 at 08:24
  • @Raman is it possible to do the above? – Sourav Jha Sep 21 '21 at 18:18
  • @SouravJha No, there is no "global" way to do it for plugins that do not yet understand toolchains directly (see https://docs.gradle.org/current/userguide/toolchains.html#sec:plugins). See my answer for how to configure a plugin manually, assuming it supports such configuration. – Raman Sep 21 '21 at 22:30
  • how do any of these answers tell gradle where the java 11 jre is located? – john k Feb 28 '22 at 20:17
  • 1
    @johnktejik Gradle attempts to auto-detect the location via several common mechanisms (see https://docs.gradle.org/current/userguide/toolchains.html#sec:auto_detection). You can also define custom locations if the auto-detection isn't sufficient (see https://docs.gradle.org/current/userguide/toolchains.html#sec:custom_loc). – Raman Mar 01 '22 at 05:20
  • As of version 7.6 Gradle will also attempt to download Java when necessary, defaulting to the Adoptium/AdoptOpenJDK distributions. – Jur_ Dec 05 '22 at 12:23
62

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

jfk
  • 4,335
  • 34
  • 27
  • 1
    Does this solution still work if you open a terminal and run gradle build? Or is this solution only used when using the IDE to run/compile code? – Johann Oct 15 '21 at 08:03
  • 2
    This is for the IDE – jfk Oct 15 '21 at 08:24
  • 1
    @Johann yes. This can work from some terminal uses of gradle: https://stackoverflow.com/questions/67079327/how-can-i-fix-unsupported-class-file-major-version-60-in-intellij-idea/67101848#comment128424269_67101848 – ScottWelker Jun 22 '22 at 22:54
  • There is no such option in the Gradle settings in 2023. – havryliuk Mar 15 '23 at 09:40
30

If you are executing using gradle wrapper, you can run the command with JDK path like following

./gradlew -Dorg.gradle.java.home=/jdk_path_directory

Vittal Pai
  • 3,317
  • 25
  • 36
17

You could easily point your desired Java version with specifying in the project level gradle.properties. This would effect the current project rather than altering the language level for every project throughout the system.

org.gradle.java.home=<YOUR_JDK_PATH>
Yekta Sarıoğlu
  • 1,435
  • 2
  • 12
  • 20
  • 1
    didnt work. `Value 'C:Program FilesJavajdk-11.0.8' given for org.gradle.java.home Gradle property is invalid (Java home supplied is invalid)` Please provide examples. – john k Feb 28 '22 at 20:25
  • escape the backslashes like so org.gradle.java.home=C:\\Program Files\\Java\\jdk-11.0.8 – JPA Apr 10 '22 at 12:17
  • 1
    Tried something like "org.gradle.java.home=C\:\\Program Files\\Java\\jdk-11.0.16.1", but it won't work. However, something like this works: "./gradlew -Dorg.gradle.java.home="C:\Program Files\Java\jdk-11.0.15" build" – MadHatter Sep 09 '22 at 02:45
  • This may be a sensitive private information about path of the development machine. How to deal with it? – Lucas Sousa Apr 19 '23 at 02:25
10

If you are using linux and gradle wrapper you can use following solution.

Add path to local.properties file:

javaHome=<path to JDK>

Add to your gradlew script file:

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
source $DIR/local.properties 2>/dev/null

if ! [ -z "$javaHome" ]
then
  JAVA_HOME=$javaHome
fi

In this solution, each developer can set his own JDK path. File local.properties shouldn't be included in version control system.

m0j0hn
  • 532
  • 4
  • 16
sylwano
  • 467
  • 4
  • 9
  • Bumped into the same problem as OP (being forced to meddle with old project whom the original developer has left), this is the best solution for me so far – Bondan Sebastian Aug 25 '20 at 11:59
  • Using another environment variable instead of writing it in the local.properties file can also do the same job. – firemaples Dec 08 '20 at 06:27
  • This makes your gradlew installation work differently than in projects made by other people, adding a stumbling block for every new collaborator. – toolforger Sep 19 '22 at 20:58
10

If you are using JDK 9+, you can do this:

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

tasks.withType<JavaCompile> {
    options.compilerArgs.addAll(arrayOf("--release", "8"))
}

You can also see the following related issues:

Rosberg Linhares
  • 3,537
  • 1
  • 32
  • 35
8

There is one more option to follow. In your gradle tasks available in Eclipse, you can set your desired jdk path. (I know this is a while since the question was posted. This answer can help someone.)

Right click on the deploy or any other task and select "Open Gradle Run Configuration..."

enter image description here

Then navigate to "Java Home" and paste your desired java path.

enter image description here

Please note that, bin will be added by the gradle task itself. So don't add the "bin" to the path.

Kiran
  • 1,177
  • 4
  • 18
  • 35
7

For windows run gradle task with jdk 11 path parameter in quotes

gradlew clean build -Dorg.gradle.java.home="c:/Program Files/Java/jdk-11"
6

I added this line in my GRADLE_HOME/bin/gradle file - export JAVA_HOME=/path/to/java/version

Manoj
  • 644
  • 12
  • 21
6

For Windows, open cmd and enter to your project root, then execute a command like this:

gradlew build -Dorg.gradle.java.home="jdk_path"

My JDK is located in this path: C:\Program Files\Java\jdk-11.0.5.

So, for my case, it looks like this below:

gradlew build -Dorg.gradle.java.home="C:\Program Files\Java\jdk-11.0.5"

Additionally, if you want to specify a certain variant, you can do like this :

gradlew assembleDebug -Dorg.gradle.java.home="E:\AndroidStudio\jre"

This command will compile your project with Debug variant and output 2 apks(debug + release) in 2 folders.

Chinese Cat
  • 5,359
  • 2
  • 16
  • 17
4
*gradle.properties
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
org.gradle.java.home=C\:\\Program Files\\Java\\jdk-11.0.15
-------------------------------------------------------------------
**build.gradle**
android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion
    compileOptions {
        sourceCompatibility 11
        targetCompatibility 11
    }
    kotlinOptions {
        jvmTarget = '11'
        useIR = true
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }*

after flutter3.0 & jdk11 install these steps worked for me

btm me
  • 368
  • 3
  • 11
3

there is a Gradle plugin that download/bootstraps a JDK automatically:

https://plugins.gradle.org/plugin/com.github.rmee.jdk-bootstrap

No IDE integration yet and a decent shell required on Windows.

Remo Meier
  • 141
  • 2
  • Where "decent shell" means bash, basically. I just submitted a PR to make it work for the batch file too. – Hakanai Feb 18 '22 at 23:32
2

As seen in Gradle (Eclipse plugin)

http://www.gradle.org/get-started

Gradle uses whichever JDK it finds in your path (to check, use java -version). Alternatively, you can set the JAVA_HOME environment variable to point to the install directory of the desired JDK.


If you are using this Eclipse plugin or Enide Studio 2014, alternative JAVA_HOME to use (set in Preferences) will be in version 0.15, see http://www.nodeclipse.org/history

Paul Verest
  • 60,022
  • 51
  • 208
  • 332
  • 1
    Hi Paul, actually, exactly this is my problem. I want to define a different JDK for gradle-building tasks than defined in JAVA_HOME. Though, it's good to know that there will be an entry in the eclipse plugin for this :) – bully Apr 01 '14 at 10:21
  • Standard Eclipse allows to define environment variables per launch configuration. But that is not what we try with gradle. Open an issue if you explore this question further https://github.com/Nodeclipse/nodeclipse-1/issues – Paul Verest Apr 02 '14 at 05:28
2

If you just want to set it once to run a specific command:

JAVA_HOME=/usr/lib/jvm/java-11-oracle/ gw build
JasonBodnar
  • 135
  • 8
2

So, I use IntelliJ for my Android project, and the following solved the issue in the IDE:

just cause it might save someone the few hours I wasted... IntelliJ -> Preferences -> Build, Execution, Deployment -> Build tools -> Maven -> Gradle

and set Gradle JVM to 1.8 make sure you also have JDK 8 installed...

NOTE: the project was compiling just fine from the command line

TacB0sS
  • 10,106
  • 12
  • 75
  • 118
2

There is a pretty simple way. You can try the following solution.

sudo update-alternatives --config java

After updating your java version, let check Gradle current JVM's version to ensure this change was applied.

gradle -v

For more details, pls review your gradlew file (in Unix-like OS) or gradlew.bat file (in Window OS) to see how Gradle config JAVACMD variable.

For example

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
logbasex
  • 1,688
  • 1
  • 16
  • 22
1

Android Studio

File > Project Structure > SDK Location > JDK Location >

/usr/lib/jvm/java-8-openjdk-amd64

GL

Install JDK

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
1

If you are using Kotlin DSL, then in build.gradle.kts add:

tasks.withType<JavaCompile> {
    options.isFork = true
    options.forkOptions.javaHome = File("C:\\bin\\jdk-13.0.1\\")
}

Of course, I'm assuming that you have Windows OS and javac compiler is in path C:\bin\jdk-13.0.1\bin\javac. For Linux OS will be similarly.

sobczak.dev
  • 973
  • 7
  • 11
0

I am using Gradle 4.2 . Default JDK is Java 9. In early day of Java 9, Gradle 4.2 run on JDK 8 correctly (not JDK 9).

I set JDK manually like this, in file %GRADLE_HOME%\bin\gradle.bat:

@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%..

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

@rem VyDN-start.
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_144\
@rem VyDN-end.

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%


@rem VyDN-start.
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_144\
@rem VyDN-end.


set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:init
@rem Get command-line arguments, handling Windows variants

if not "%OS%" == "Windows_NT" goto win9xME_args

:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2

:win9xME_args_slurp
if "x%~1" == "x" goto execute

set CMD_LINE_ARGS=%*

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\lib\gradle-launcher-4.2.jar

@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.launcher.GradleMain %CMD_LINE_ARGS%

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega
Vy Do
  • 46,709
  • 59
  • 215
  • 313
0

Thanks to this answer I was able to identify that my issue was gradle picking the wrong JDK even if the JAVA_HOME was set correctly.

My original comment:

My OS is Linux and I have my JAVA_HOME pointing to the correct path. I have even used this command gradle build -Dorg.gradle.java.home=$JAVA_HOME to prove my point. I've installed gradle using snap in Ubuntu and I'm guessing it is using some bundled JDK.

My solution:

I've removed gradle using snap and then I've manually installed gradle by downloading their binaries and put it in the PATH.

My conclusion is that the gradle snap installation on Ubuntu comes bundled with some older JDK.

IamDOM
  • 262
  • 3
  • 8