Search code examples
androidandroid-studiocode-inspection

Why can I not check instance type after class cast exception?


Can anybody explain to me why the following block of code is highlighted as a mistake in Android Studio?

The IDE is saying elem instanceof SubtypeB is always false - is this just a mistake by the inspector or is this a real language detail I need to learn about?. Can I safely suppress the warning and keep the current code?

Example code:

for (Parcelable elem : list) {
    try {
        listOfSubtypeA.add( (SubtypeA) elem );
    } catch (ClassCastException cce) {
        //Line below is highlighted as always false
        if (elem instanceof SubtypeB) {
            ... //just logging
        }
    }
}

Solution

  • It is incorrect from your IDE. Just run it:

     interface Test123  { }
    static class SubtypeA implements Test123{ }
    static class SubtypeB implements Test123 { }
    
    public static void main(String[] args) {
        List<Test123> list = new ArrayList<>();
        list.add(new SubtypeB());
        List<SubtypeA> subList = new ArrayList<>();
    
        for (Test123 elem : list) {
            try {
                subList.add( (SubtypeA) elem );
            } catch (ClassCastException cce) {
                //Line below is highlighted as always false
                if (elem instanceof SubtypeB) {
                    System.out.println("cce = " + cce);
            //just logging
                }
            }
        }
    }
    

    You will see that the statement if (elem instanceof SubtypeB) turns out to be true so your IDE doesn't detect it correct