Android混用Debug与Release库时出现重复类错误求助
解决Duplicate class MainClass问题
原因分析
Android库的每个变体(debug/release)默认会包含main源码集的所有代码,因此你的my-library-debug(debug变体)中同时包含DebugClass和MainClass;而my-library(release变体)也包含MainClass。当应用构建时,若某个变体同时引入了这两个库的产物,就会触发重复类报错。
解决方案
方案1:调整库的变体依赖关系(推荐)
在Android库的build.gradle.kts(或build.gradle)中,配置debug变体依赖release变体的产物,避免重复打包MainClass:
android { publishing { singleVariant("release") { withSourcesJar() } singleVariant("debug") { withSourcesJar() dependencies { implementation(project(mapOf("path" to ":implementation", "configuration" to "releaseRuntimeElements"))) } } } }
旧版Groovy配置写法:
android { publishing { singleVariant 'release' { withSourcesJar() } singleVariant 'debug' { withSourcesJar() dependencies { implementation project(path: ':implementation', configuration: 'releaseRuntimeElements') } } } }
配置后,my-library-debug只会包含DebugClass,MainClass复用release变体的内容,彻底避免重复。
方案2:拆分独立核心模块
将MainClass所在的main源码集拆为单独的core模块,让debug和release模块都依赖该核心模块。这样两个变体的产物都不会包含MainClass,从根源上消除重复。
方案3:检查应用的依赖配置
确认应用是否在implementation全局配置中也引入了my-library——debug构建时会同时加载debugImplementation的my-library-debug和implementation的my-library,导致重复。仅保留变体专属依赖:
// 移除implementation中的my-library依赖 debugImplementation("my-library-debug") releaseImplementation("my-library")
方案4:临时排除重复类(不推荐)
若上述方案暂时无法实施,可在应用的依赖中排除重复类来源:
debugImplementation("my-library-debug") { exclude(group = "你的库groupId", module = "my-library") } releaseImplementation("my-library")
验证步骤
- 执行
./gradlew clean清理库和应用的构建缓存 - 重新构建并发布库到本地仓库(或同步依赖)
- 重新构建应用,确认报错消失
内容的提问来源于stack exchange,提问作者Paul S
相关产品推荐
相关产品推荐

