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

升级AGP 8.0后开启混淆时Retrofit抛出类型转换异常求助

解决AGP 8.0 + Retrofit 混淆后ClassCastException问题

问题根源

AGP 8.0默认启用R8 full mode,该模式会剥离未显式保留的类/接口的泛型签名信息。Retrofit通过反射解析API接口的泛型类型(比如Call<ResponseData>或suspend函数的返回值泛型),当这些泛型签名被剥离后,就会抛出ClassCastException: Class cannot be cast to ParameterizedType。

完整解决方案

1. 补充ProGuard规则

在proguard-rules.pro中添加以下规则,确保关键类的泛型签名和类型信息被保留:

# 保留泛型签名、内部类等核心属性(R8 full mode下必须显式声明)
-keepattributes Signature, InnerClasses, EnclosingMethod

# 保留所有API接口的方法及泛型信息(替换为你的接口包路径)
-keep,allowobfuscation,allowshrinking interface com.iku.data.network.service.** {
    <methods>;
}

# 保留Moshi相关类的泛型适配能力
-keep,allowobfuscation,allowshrinking class com.squareup.moshi.** {
    <methods>;
}
-keep,allowobfuscation,allowshrinking interface com.squareup.moshi.** {
    <methods>;
}

# 保留原有Retrofit相关规则
-keep,allowobfuscation,allowshrinking interface retrofit2.Call
-keep,allowobfuscation,allowshrinking class retrofit2.Response
-keep,allowobfuscation,allowshrinking class kotlin.coroutines.Continuation

2. 升级依赖版本(可选但推荐)

将OkHttp从alpha版本替换为稳定版,避免兼容性问题:

// OkHttp 稳定版替换alpha版本
implementation 'com.squareup.okhttp3:okhttp:4.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0'

3. 验证R8配置

确保gradle.properties中R8 full mode处于启用状态(AGP8.0默认开启,无需修改):

android.enableR8.fullMode=true

原理说明

  • -keepattributes Signature:强制保留类/方法的泛型签名,这是Retrofit反射解析泛型的核心依赖。
  • 保留API接口方法:避免R8优化掉接口的方法签名和泛型参数,确保动态代理能正确解析接口定义。
  • 保留Moshi相关类:避免JSON解析时泛型类型丢失,导致反序列化失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:52:00