Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce a java compiler version with gradle?

Tags:

java

gradle

javac

In all of my projects, I use gradle and specify the following:

sourceCompatibility = "1.7"; // for example
targetCompatibility = "1.7"; // defaults to sourceCompatibility

Now, I have three different versions of the JDK installed, from 1.6 to 1.8. In order to switch from one version to another, I source shell files to change PATH, JAVA_HOME and even JDK_HOME.

By accident it can happen that I use the wrong JDK version and I don't want that... Is there a possibility to check that the compiler version is equal to targetCompatibility before attempting any compilation task?

like image 630
fge Avatar asked Jan 21 '15 10:01

fge


People also ask

How do I set Java version in build Gradle?

Right click on the deploy or any other task and select "Open Gradle Run Configuration..." Then navigate to "Java Home" and paste your desired java path.

Which Java version is Gradle using?

Gradle can only run on Java version 8 or higher. Gradle still supports compiling, testing, generating Javadoc and executing applications for Java 6 and Java 7.

Is Gradle compatible with Java 11?

The minimum version of Gradle that supports Java 11 is 5.0 . You would need to upgrade to version 7.0 or above for Android.

Which Gradle version is compatible with Java 17?

As of Gradle 7.3, both running Gradle itself and building JVM projects with Java 17 is fully supported.


1 Answers

Answer to self, and thanks to @JBNizet for providing the initial solution...

The solution is indeed to use JavaVersion, and it happens that both sourceCompatibility and targetCompatibility accept a JavaVersion as an argument...

Therefore the build file has become this:

def javaVersion = JavaVersion.VERSION_1_7;
sourceCompatibility = javaVersion;
targetCompatibility = javaVersion; // defaults to sourceCompatibility

And then the task:

task enforceVersion << {
    def foundVersion = JavaVersion.current();
    if (foundVersion != javaVersion) 
        throw new IllegalStateException("Wrong Java version; required is "
            + javaVersion + ", but found " + foundVersion);
}

compileJava.dependsOn(enforceVersion);

And it works:

$ ./gradlew clean compileJava
:clean UP-TO-DATE
:enforceVersion FAILED

FAILURE: Build failed with an exception.

* Where:
Build file '/home/fge/src/perso/grappa-tracer-backport/build.gradle' line: 55

* What went wrong:
Execution failed for task ':enforceVersion'.
> Wrong Java version; required is 1.7, but found 1.8
like image 114
fge Avatar answered Oct 21 '22 02:10

fge