Gradle 构建时出现 "Error while dexing" 的解决方法
问题描述
在 Gradle 构建过程中遇到以下报错:
log
> Could not resolve all files for configuration ':MyPlugin:debugRuntimeClasspath'.
> Failed to transform commons-lang3-3.14.0.jar
> Execution failed for DexingNoClasspathTransform
> Error while dexing.
该错误通常出现于以下场景:
- 项目长时间未更新后重新构建
- 环境配置发生变更(如 JDK 升级)
- 依赖库版本冲突
- AGP/Gradle 版本不兼容
错误表现可能包括:
- 构建失败的 dexing 错误日志
- 出现
NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null
- 清理缓存(
./gradlew clean
或删除~/.gradle/caches
)无效
解决方案
1. 切换至 JDK 17
使用 JDK 21 可能导致兼容性问题:
操作步骤
- 下载 JDK 17
- Android Studio:
- Settings → Build, Execution, Deployment → Build Tools → Gradle
- 将 Gradle JDK 改为 JDK 17
- 命令行环境:配置
JAVA_HOME
环境变量指向 JDK 17
2. 升级 AGP 和 Gradle 版本
修改 gradle-wrapper.properties
:
properties
# 使用 Gradle 8.4
distributionUrl=https://services.gradle.org/distributions/gradle-8.4-bin.zip
修改项目级 build.gradle
:
groovy
// AGP 8.1+ 使用 plugins 块
plugins {
id 'com.android.application' version '8.3.1' apply false
}
3. 修复依赖库问题
问题库降级
groovy
dependencies {
// 替换有问题的版本
implementation 'org.apache.commons:commons-lang3:3.13.0' // 替代 3.14.0
}
避免动态版本声明
diff
dependencies {
- implementation 'androidx.core:core-ktx:+'
+ implementation "androidx.core:core-ktx:1.12.0"
}
移除无关依赖
检查并移除 pubspec.yaml
中不需要的库:
yaml
# 删除无效依赖
dependencies:
# camera: any // 删除这一行
4. 确保版本一致性
groovy
// 项目级 build.gradle
plugins {
id("org.jetbrains.kotlin.android") version "1.8.20"
id("com.android.application") version "8.1.1"
}
// 模块级 build.gradle
dependencies {
implementation("androidx.core:core-ktx:1.13.1")
implementation("androidx.appcompat:appcompat:1.6.1") // ✓ 版本匹配 Kotlin 插件
}
版本不匹配的典型报错
当 AGP/Kotlin 插件版本与依赖库不兼容时,会触发:
java.lang.NullPointerException:
Cannot invoke "String.length()" because "<parameter1>" is null
常见原因说明
- JDK 兼容性问题:Android 工具链目前主要适配 JDK 17,JDK 21 中的变化可能导致 dex 处理异常
- 依赖冲突:库的新版本可能引入不兼容变更,特别是主版本号的升级
- 工具链更新滞后:AGP 和 Gradle 的旧版本无法正确处理新发布的依赖库
- 动态版本风险:
+
或any
可能意外引入破坏性更新
建议工作流程
关键原则:优先尝试 AGP/Gradle升级方案,这是最彻底的解决方案。若受项目约束无法升级,再使用依赖降级作为临时措施。