One of my project requires Java 1.8, but sometimes we didn't notice we are using older java so that we will get some strange errors.
I want to add the checking in build.gradle
, so that when we run any task, it will firstly check the version, and prints error and quit immediately.
I tried to add the checking directly in build.gradle
on the first line, but it still do some others tasks e.g. (clean
, compileJava
) before the checking happens, when I run:
$ ./gradlew
How to do it correctly?
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.
Gradle requires a Java JDK or JRE to be installed, version 6 or higher (to check, use java -version ). Gradle ships with its own Groovy library, therefore Groovy does not need to be installed. Any existing Groovy installation is ignored by Gradle. Gradle uses whatever JDK it finds in your path.
Gradle uses whatever JDK it finds in your path. Alternatively, you can set the JAVA_HOME environment variable to point to the installation directory of the desired JDK. See the full compatibility notes for Java, Groovy, Kotlin and Android.
Android Gradle plugin requires Java 11 to run.
If you put the check very early in your build lifecycle (plain check in the beginning of your build.gradle
file or in the apply method of a plugin) you shouldn't see any tasks executed.
you can use JavaVersion enum for that which is part of the gradle api:
if(JavaVersion.current() != JavaVersion.VERSION_1_8){ throw new GradleException("This build must be run with java 8") }
The accepted answer is nice however it could be improved a little bit by making it more generic. Indeed instead of comparing the current version with an explicit version, we could rely on the value of targetCompatibility
instead (assuming it has been set properly) as next:
if (JavaVersion.current() != project.targetCompatibility) { throw new GradleException("The java version used ${JavaVersion.current()} is not the expected version ${project.targetCompatibility}.") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With