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

多模块Android项目构建报错:无法访问retrofit2.Response类

解决多模块Android项目中Retrofit Response类无法访问的构建报错

以下是针对你的情况的具体排查和解决步骤:

1. 确保依赖可传递到调用模块

定义suspend fun getProducts(): Response<ResponseBody>的服务模块,需要将Retrofit相关依赖声明为api而非implementation,这样依赖才能传递到调用它的数据源模块。修改服务模块的build.gradle.kts:

// 服务模块的build.gradle.kts
dependencies {
    api("com.squareup.retrofit2:retrofit:${libs.versions.retrofit.get()}")
    api("com.squareup.retrofit2:converter-scalars:${libs.versions.retrofit.get()}") // 若使用ResponseBody需添加此依赖
    // 其他依赖...
}

如果服务模块用了implementation,则数据源模块必须自行添加Retrofit的implementation依赖。

2. 校验TOML版本配置的一致性

检查libs.versions.toml中Retrofit的版本声明是否正确,确保所有模块引用的是同一版本:

[versions]
retrofit = "2.11.0"

[libraries]
retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
retrofit-converter-scalars = { group = "com.squareup.retrofit2", name = "converter-scalars", version.ref = "retrofit" }

避免模块中硬编码其他版本的Retrofit导致依赖冲突。

3. 清理构建缓存并强制刷新依赖

IDE无报错但构建失败往往是缓存问题,执行以下操作:

  • 点击Android Studio菜单栏File > Invalidate Caches... > Invalidate and Restart
  • 终端执行命令:
    ./gradlew clean build --refresh-dependencies
    

强制清理缓存并重新拉取依赖。

4. 确认模块间依赖关系正确

数据源模块的build.gradle.kts必须正确依赖服务模块,检查是否有拼写错误:

// 数据源模块的build.gradle.kts
dependencies {
    implementation(project(":service-module-name")) // 替换为你的服务模块名称
    // 其他依赖...
}

同时确保settings.gradle.kts中已正确包含所有模块。

5. 统一JDK与Kotlin编译配置

所有模块的编译配置需保持一致,避免版本不兼容:

// 每个模块的build.gradle.kts中添加
android {
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }
    kotlinOptions {
        jvmTarget = "17"
    }
}

6. 排查依赖冲突

执行命令查看数据源模块的依赖树,检查是否存在Retrofit版本冲突:

./gradlew :data-source-module-name:dependencies

若发现冲突,在根build.gradle.kts或数据源模块中强制统一版本:

configurations.all {
    resolutionStrategy.force("com.squareup.retrofit2:retrofit:${libs.versions.retrofit.get()}")
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:17:12