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

如何解决Gradle嵌套依赖库中的‘Duplicate class’问题

解决Gradle依赖重复类问题的可行方案

第一步:定位冲突依赖的完整来源

先通过Gradle命令打印依赖树,明确所有引入com.y.lib的上层库:

# 普通Java项目
./gradlew dependencies --configuration implementation

# Android项目(替换app为你的模块名)
./gradlew app:dependencies --configuration debugImplementation

在输出结果中搜索com.y.lib,就能找到包括游戏引擎内置库在内的所有引入路径,确认冲突版本的来源。

第二步:精准排除冲突模块

你之前的exclude写法错误,因为Gradle的exclude是针对整个模块/组,而非单个类。正确做法是找到引入旧版本com.y.lib:1.2.3的上层依赖(即com.x.somelib),排除整个com.y.lib模块:

dependencies {
    implementation('com.x.somelib') {
        exclude group: 'com.y', module: 'lib'
    }
}

这样com.x.somelib会放弃自带的com.y.lib:1.2.3,转而使用项目中已存在的com.y.lib:1.3.2。

第三步:兼容性问题的兜底方案——重命名冲突类

如果排除旧版本后,com.x.somelib出现NoClassDefFoundError,说明它与com.y.lib:1.3.2不兼容,可使用Gradle Shadow插件重命名冲突类的包名:

  1. 引入Shadow插件(Android项目适用):
plugins {
    id 'com.android.application' // 或com.android.library
    id 'com.github.johnrengelman.shadow' version '8.1.1'
}
  1. 配置重命名规则:
shadowJar {
    // 将冲突包重命名为新路径
    relocate 'com.android.somelib', 'com.android.somelib.shadowed'
}

执行./gradlew shadowJar生成重命名后的Jar包,替换原依赖即可规避类重复。

第四步:强制替换冲突版本的高级配置

如果常规force无效,可能是游戏引擎依赖被锁定,可使用依赖替换策略强制全局替换版本:

configurations.all {
    resolutionStrategy {
        dependencySubstitution {
            substitute module('com.y.lib:1.2.3') with module('com.y.lib:1.3.2')
        }
    }
}

该配置会将所有引入的com.y.lib:1.2.3强制替换为1.3.2,无视上层依赖的版本声明。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:10:25