You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gradle Kotlin DSL子项目Java配置报错,如何统一设置JDK17?

修复Gradle Kotlin DSL中统一子项目Java版本17的配置错误

我希望将所有子项目的Java版本统一设置为17,主项目的build.gradle.kts配置如下:

group = "org.example"
version = "1.0-SNAPSHOT"

subprojects {
    apply(plugin = "java")
    repositories {
        mavenCentral()
        mavenLocal()
    }

    configure<JavaCompile> {
        targetCompatibility = JavaVersion.VERSION_17.toString()
        sourceCompatibility = JavaVersion.VERSION_17.toString()
    }

    java {
        toolchain {
            languageVersion.set(JavaLanguageVersion.of(17))
        }
    }
}

执行gradle clean build时出现以下错误:

% gradle clean build

Configure project :
e: file:///Users/rnatarajan/Documents/Coding/others/org-example/build.gradle.kts:28:5: Expression 'java' cannot be invoked as a function. The function 'invoke()' is not found
e: file:///Users/rnatarajan/Documents/Coding/others/org-example/build.gradle.kts:28:5: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val PluginDependenciesSpec.java: PluginDependencySpec defined in org.gradle.kotlin.dsl
e: file:///Users/rnatarajan/Documents/Coding/others/org-example/build.gradle.kts:29:9: Unresolved reference: toolchain
e: file:///Users/rnatarajan/Documents/Coding/others/org-example/build.gradle.kts:30:13: Unresolved reference: languageVersion

FAILURE: Build failed with an exception.


错误原因

原配置中java {}是Gradle Groovy DSL的写法,在Kotlin DSL中不支持直接这样调用,需要通过JavaPluginExtension扩展来配置Java工具链。

修复后的配置

推荐两种修复方式,第二种更简洁:

方式一:保留兼容性配置 + 正确配置工具链

group = "org.example"
version = "1.0-SNAPSHOT"

subprojects {
    apply(plugin = "java")
    repositories {
        mavenCentral()
        mavenLocal()
    }

    tasks.withType<JavaCompile> {
        sourceCompatibility = JavaVersion.VERSION_17.toString()
        targetCompatibility = JavaVersion.VERSION_17.toString()
    }

    // 替换原有的java{}块,通过JavaPluginExtension配置工具链
    configure<JavaPluginExtension> {
        toolchain {
            languageVersion.set(JavaLanguageVersion.of(17))
        }
    }
}

方式二:仅用工具链配置(自动同步兼容性版本)

配置Java工具链后,Gradle会自动将sourceCompatibility和targetCompatibility同步为工具链指定的版本,因此可以去掉单独的编译兼容性配置:

group = "org.example"
version = "1.0-SNAPSHOT"

subprojects {
    apply(plugin = "java")
    repositories {
        mavenCentral()
        mavenLocal()
    }

    configure<JavaPluginExtension> {
        toolchain {
            languageVersion.set(JavaLanguageVersion.of(17))
        }
    }
}

验证

修改配置后,重新执行gradle clean build即可正常完成编译,所有子项目都会使用Java 17版本进行构建。

内容的提问来源于stack exchange,提问作者user51

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 03:46:30