ClassCastException:应用程序对象不是我的自定义应用程序对象

ClassCastException: Application object is not my custom application object

通常在 Android 代码中,我们使用这种模式将数据存储在 Application 对象中,然后通过强制转换访问它:

((MyApplicationObject)getApplication()).getDaggerComponent()

getApplication() 应该总是 MyApplicationObject 因为我在 AndroidManifest.xml 中指定了它。但是,当您部署此代码时,有时它会导致 ClassCastException 而我们得到一个不同的对象。

怎么会这样?

此问题的正确解决方法是什么?

已在评论中解决:这是一个 Android 错误,与 Dagger 无关。

Thank you for that link! 98% of the crashes are from Android 7.0, with 0.2% from Android 7.1. In the link a @google engineer says they improved things in major issues in 7.0, but didn't completely fix it. – gregm

查看此 public Google IssueTracker link, #37137009: java.lang.ClassCastException: Cannot cast android.app.Application to com.xxx.xxApplication (ctate's comment in #17):

Yes, this is a known issue; and was largely addressed in 7.1. There are still some edge cases in 7.1 that can result in similar circumstances -- as you can see from your analytics -- but the window of opportunity is much narrower, and Android 8 addressed those as well.

不幸的是,目前似乎没有太多的解释或官方解决方法,但至少问题的范围主要限于 Android 7.0。