androidclassloaderclasscastexceptionandroid-multidexdexclassloader

Strange ClassCastException in findViewById


I observe a weird exception thrown on line:

viewPager = (ViewPager) view.findViewById(R.id.pager);

the exception looks as follows:

java.lang.ClassCastException: android.support.v4.view.ViewPager cannot be cast to android.support.v4.view.ViewPager

I can't reproduce it, but it happens sometimes according to logs.

The app uses official multidex build with gradle.


Solution

  • According to the JLS, ClassCastException happens when you try to cast one class to a different class, which is quite obvious.

    What is not so obvious is what is the definition of Class identity:

    1. the classes have to be both of either class, interface or array type,
    2. they have to have the same binary name,
    3. they have to be loaded by the same effective ClassLoader

    In your case multiple ClassLoaders will most likely load the same class.