找不到根项目参数的方法 sourceCompatibility()

Could not find method sourceCompatibility() for arguments on root project

我想为 Java library which is built with Gradle. Therefore, I add the following block as documented for the Java plugin.

定义 sourcetarget compatibility
apply plugin: 'java'

// ...

compileJava {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

当我assemble项目出现以下错误时:

Could not find method sourceCompatibility() for arguments [1.7] on root project


相关

您正在尝试传递错误类型的值。 sourceCompatibilitytargetCompatibility 应该是字符串,但 JavaVersion.VERSION_1_7 不是字符串,而只是用重写的 toString() 方法枚举。这就是为什么您在异常文本中有 for arguments [1.7] 的原因。尝试这样做:

compileJava {
    sourceCompatibility JavaVersion.VERSION_1_7.toString()
    targetCompatibility JavaVersion.VERSION_1_7.toString()
}

compileJava {
    sourceCompatibility "$JavaVersion.VERSION_1_7"
    targetCompatibility "$JavaVersion.VERSION_1_7"
}

或者只是将它从 compileJava 闭包中移出到脚本主体,就像它通常使用的那样:

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7