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

Kotlin 1.7.0中classpath已废弃,求替代方案及使用示例

替代KotlinCompile废弃的classpath属性方案

Kotlin 1.7.0起,KotlinCompile任务的classpath属性被废弃,你可以通过以下两种方式替代:

1. 直接修改任务的compileClasspath属性

如果之前是直接给KotlinCompile任务追加或修改classpath,直接将classpath替换为compileClasspath即可:

原废弃写法:

tasks.withType<KotlinCompile> {
    // 废弃的写法
    classpath += files("libs/custom-library.jar")
}

替代写法:

tasks.withType<KotlinCompile> {
    compileClasspath += files("libs/custom-library.jar")
}

测试代码编译任务(KotlinTestCompile)的compileClasspath会自动关联到test Source Set的配置,上述代码会统一处理所有Kotlin编译任务,无需额外区分。

2. 配置Source Set的classpath(推荐)

更符合Gradle依赖管理规范的方式是直接配置对应Source Set的compileClasspath,或者通过dependencies块声明依赖,让Gradle自动维护classpath:

方式A:直接配置Source Set

sourceSets {
    main {
        // 给主代码编译classpath追加本地Jar
        compileClasspath += files("libs/custom-library.jar")
    }
    test {
        // 给测试代码编译classpath追加本地Jar
        compileClasspath += files("libs/test-utils.jar")
    }
}

方式B:通过依赖配置声明(最推荐)

如果是本地Jar或远程依赖,直接在dependencies块中声明,Gradle会自动将其加入对应Source Set的compileClasspath和runtimeClasspath:

dependencies {
    // 主代码依赖本地Jar
    implementation(files("libs/custom-library.jar"))
    // 测试代码依赖本地Jar
    testImplementation(files("libs/test-utils.jar"))
    // 远程依赖示例
    implementation("com.example:some-library:1.0.0")
}

为什么要这样替换?

废弃classpath属性是因为它属于任务的内部属性,直接修改容易导致依赖配置不一致。而compileClasspath是和Source Set绑定的标准属性,遵循Gradle的依赖管理模型,能保证编译时的classpath和运行时、测试时的依赖配置保持一致,同时兼容后续Kotlin和Gradle版本。

内容的提问来源于stack exchange,提问作者H.Michi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:22:23