Reputation: 198368
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?
Upvotes: 34
Views: 55725
Reputation: 45005
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}.")
}
Upvotes: 12
Reputation: 28663
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")
}
Upvotes: 61