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

2022-09-02 23:44:55

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

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

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

偶然地,我可能会发生我使用错误的JDK版本,我不想要那个......在尝试任何编译任务之前,是否有可能检查编译器版本是否等于目标兼容性?


答案 1

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

解决方案确实是使用JavaVersion,并且碰巧两者都接受a作为参数...sourceCompatibilitytargetCompatibilityJavaVersion

因此,构建文件已变为:

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

答案 2

我使用以下:

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

推荐