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

Android项目Gradle编程获取依赖报错求助(Gradle 7.5)

问题

在Android项目中,我想通过Gradle以编程方式获取依赖,在项目级和模块级build.gradle中尝试了以下代码:

task dumpDependencies {
    doLast {
        def resolved = configurations.compileClasspath.resolvedConfiguration
        println "Files: $resolved.files"
    }
}

运行后出现错误:

> Could not get unknown property 'compileClasspath' for configuration container of type org.gradle.api.internal.artifacts.configurations.DefaultConfigurationContainer.

使用的Gradle版本为7.5,配置如下:

distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip

请问遗漏了什么?

解答

  • Android Gradle插件的配置名称已变更
    从Android Gradle插件3.0版本开始,原有的compile配置被废弃,替换为implementation、api等更细分的依赖配置,对应的编译类路径配置也从compileClasspath改为与变体绑定的名称,比如debugCompileClasspath(debug变体)、releaseCompileClasspath(release变体)。直接使用旧的compileClasspath会找不到对应配置。

  • 项目级构建脚本不支持Android模块配置
    项目级build.gradle是全局配置文件,不存在Android模块特有的配置集合,因此在这里访问compileClasspath必然报错,必须在模块级的build.gradle中进行操作。

  • 修正后的代码示例
    在模块级build.gradle中使用以下代码,可获取debug变体的依赖文件:

    task dumpDependencies {
        doLast {
            def resolved = configurations.debugCompileClasspath.resolvedConfiguration
            println "Debug依赖文件列表:"
            resolved.files.each { file ->
                println file.absolutePath
            }
        }
    }
    

    如果需要获取所有变体的依赖,可以遍历Android变体生成对应任务:

    android {
        applicationVariants.all { variant ->
            task "dump${variant.name.capitalize()}Dependencies" {
                doLast {
                    def resolved = configurations."${variant.name}CompileClasspath".resolvedConfiguration
                    println "${variant.name}依赖文件列表:"
                    resolved.files.each { file ->
                        println file.absolutePath
                    }
                }
            }
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:23:21