How do I tell Gradle to use specific JDK version?

JavaGradlebuild.gradle

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

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
}

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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>

Solution 8 - Java

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.

Solution 9 - Java

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.

Solution 10 - Java

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:

Solution 11 - Java

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

Solution 12 - Java

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"

Solution 13 - Java

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.

Solution 14 - Java

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.

Solution 15 - Java

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>

Solution 16 - Java

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

Solution 17 - Java

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

Solution 18 - Java

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

JAVA_HOME=/usr/lib/jvm/java-11-oracle/ gw build

Solution 19 - Java

Android Studio

File > Project Structure > SDK Location > JDK Location >

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

GL

Install JDK

Solution 20 - Java

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.

Solution 21 - Java

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

Solution 22 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbullyView Question on Stackoverflow
Solution 1 - JavaFirst ZeroView Answer on Stackoverflow
Solution 2 - JavamirmdasifView Answer on Stackoverflow
Solution 3 - JavaGeertView Answer on Stackoverflow
Solution 4 - JavaRamanView Answer on Stackoverflow
Solution 5 - JavaJafar KaruthedathView Answer on Stackoverflow
Solution 6 - JavaVittal PaiView Answer on Stackoverflow
Solution 7 - JavaYekta SarıoğluView Answer on Stackoverflow
Solution 8 - JavasylwanoView Answer on Stackoverflow
Solution 9 - JavaKiranView Answer on Stackoverflow
Solution 10 - JavaRosberg LinharesView Answer on Stackoverflow
Solution 11 - JavaManojView Answer on Stackoverflow
Solution 12 - JavaSergey AlekhinView Answer on Stackoverflow
Solution 13 - JavaChinese CatView Answer on Stackoverflow
Solution 14 - JavaRemo MeierView Answer on Stackoverflow
Solution 15 - JavaPaul VerestView Answer on Stackoverflow
Solution 16 - JavaTacB0sSView Answer on Stackoverflow
Solution 17 - JavalogbasexView Answer on Stackoverflow
Solution 18 - JavaJasonBodnarView Answer on Stackoverflow
Solution 19 - JavaBraian CoronelView Answer on Stackoverflow
Solution 20 - Javasobczak.devView Answer on Stackoverflow
Solution 21 - JavaJames GrahamView Answer on Stackoverflow
Solution 22 - JavaIamDOMView Answer on Stackoverflow