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

How to enforce a java compiler version with gradle?

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

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

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

我可能会意外地使用错误的 JDK 版本,而我不想那样...是否有可能在尝试任何编译任务之前检查编译器版本是否等于 targetCompatibility ?

我使用以下:

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

自我解答,感谢提供初步解决方案...

解决方案确实是使用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

如果您希望所有任务都检查版本,您可以在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"