Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check java version when running gradle?

Tags:

gradle

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?

like image 442
Freewind Avatar asked Jan 21 '15 06:01

Freewind


People also ask

How does Gradle know which Java?

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.

Does Gradle need JDK or JRE?

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.

Does Gradle use JAVA_HOME?

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.

Does Gradle work with Java 11?

Android Gradle plugin requires Java 11 to run.


2 Answers

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") } 
like image 61
Rene Groeschke Avatar answered Oct 12 '22 10:10

Rene Groeschke


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}.") } 
like image 21
Nicolas Filotto Avatar answered Oct 12 '22 10:10

Nicolas Filotto