如何使用gradle强制执行java编译器版本?

时间:2015-01-21 10:57:38

标签: java gradle javac

在我的所有项目中,我使用gradle并指定以下内容:

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

现在,我安装了三个不同版本的JDK,从1.6到1.8。为了从一个版本切换到另一个版本,我source个shell文件要更改PATHJAVA_HOME甚至JDK_HOME

偶然会发生我使用错误的JDK版本并且我不想要...在尝试任何编译任务之前是否有可能检查编译器版本是否等于targetCompatibility?

3 个答案:

答案 0 :(得分:16)

回答自我,并感谢@JBNizet提供初始解决方案......

解决方案确实是使用JavaVersion,并且sourceCompatibilitytargetCompatibility都接受JavaVersion作为参数......

因此构建文件已成为:

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

接下来的任务:

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

compileJava.dependsOn(enforceVersion);

它有效:

$ ./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

答案 1 :(得分:11)

我使用以下内容:

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

答案 2 :(得分:0)

如果要检查所有任务的版本,可以在build.gradle中添加一个断言以强制执行:

assert JavaVersion.current().isJava9Compatible(): "Java 9 or newer is required"

对于Gradle 5.4.1,失败看起来像这样:

$ ./gradlew --quiet build
FAILURE: Build failed with an exception.

* Where:
Build file '/home/codehearts/build.gradle' line: 15

* What went wrong:
A problem occurred evaluating root project 'Codehearts'.
> Java 9 or newer is required. Expression: org.gradle.api.JavaVersion.current().isJava9Compatible()

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s

如果需要,您还可以检查确切的版本:

assert JavaVersion.current().isJava9(): "Java 9 is required"