Search code examples
javagradlejavac

How to enforce a java compiler version with gradle?


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?


Solution

  • I use the following:

    task checkJavaVersion << {
        if (!JavaVersion.current().isJava6()) {
            String message = "ERROR: Java 1.6 required but " +
                              JavaVersion.current() +
                              " found. Change your JAVA_HOME environment variable.";
            throw new IllegalStateException(message);
        }
    }
    
    compileJava.dependsOn checkJavaVersion