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

Gradle生成的buildSrc+Kotlin项目:如何升级至Java 17并统一编译目标?

解决Kotlin与Java编译目标版本不兼容问题

问题原因

Gradle 7.x版本的Kotlin插件默认JVM目标版本是1.8,而你的环境JDK版本为17,Java插件自动沿用了JDK版本作为编译目标,导致两者版本不匹配触发提示。这个1.8是插件内置的默认值,不会显式出现在你的构建脚本里。

解决方法

全局统一配置(推荐)

在项目根目录的构建脚本中设置,让所有模块都对齐Java 17版本:

若使用Kotlin DSL(build.gradle.kts)

allprojects {
    // 配置Kotlin编译目标
    tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
        kotlinOptions.jvmTarget = "17"
    }

    // 同步Java编译兼容性
    tasks.withType<JavaCompile>().configureEach {
        sourceCompatibility = "17"
        targetCompatibility = "17"
    }
}

若使用Groovy DSL(build.gradle)

allprojects {
    // 配置Kotlin编译目标
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
        kotlinOptions.jvmTarget = '17'
    }

    // 同步Java编译兼容性
    tasks.withType(JavaCompile).configureEach {
        sourceCompatibility = '17'
        targetCompatibility = '17'
    }
}

单模块单独配置

如果只需要调整某个模块的设置,直接在该模块的构建脚本中添加:

Kotlin DSL示例

tasks.withType<KotlinCompile>().configureEach {
    kotlinOptions.jvmTarget = "17"
}

tasks.withType<JavaCompile>().configureEach {
    sourceCompatibility = "17"
    targetCompatibility = "17"
}

buildSrc的额外配置

如果你的buildSrc目录下有Kotlin代码需要编译,同样在buildSrc的build.gradle.kts中添加Kotlin编译目标的配置,确保buildSrc的编译版本也对齐17。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:11:20