Gradle and Java Version Compatibility: A Beginner's Guide
No matter how long you've been working with a technology or a platform, such as Android, you always encounter weird errors. The more time you spend, the more edge cases and new things you will learn.
I feel relatively comfortable with Gradle due to my experience with Android over the years. But I encountered a weird issue last week in a perfectly working Android project.
I could run the project just fine with Android Studio, but when running ./gradlew assembleDebug
command to generate a build it was failing with:
Execution failed for task ':app:kspDebugKotlin'.
> Error while evaluating property 'compilerOptions.jvmTarget'
of task ':app:kspDebugKotlin'.
> Failed to calculate the value of property 'jvmTarget'.
> Unknown Kotlin JVM target: 20
It was complaining that my Java version was incompatible with Gradle. You see each Gradle version is compatible with specific Java versions - see this compatibility table here (source).
But if my system's Java JDK version was incompatible with Gradle, the run should have been failing from Android Studio as well, right?
What I had missed, is that Android Studio comes with an "embedded" Java JDK and it's not using your system-installed JDK. You can see and select which JDK Android Studio is using by going to Settings
-> Build, Execution & Deployment
-> Build tools
-> Gradle
. There you can change the version, see what is the current version, and even easily download and install new JDKs with one click!
To solve my issue of running ./gradlew assembleDebug
in the command line, I needed to install the same JDK version as the embedded JDK that Android Studio was using. To change the Java version that is used in a command line session (not system-wide), just update the JAVA_HOME
environment variable for the OS you are using.
In case you are on MacOS, you can list the available JDKs in your system by running:
/usr/libexec/java_home -V
Then update the JAVA_HOME
env variable with the selected version:
export JAVA_HOME=`/usr/libexec/java_home -v 17`
And run this to confirm:
java -version
That's it! For the current terminal session, this JDK will be used, and you can run ./gradlew assembleDebug
or any other command that requires a specific Java version you want.
Happy coding!