ClassCastException for different types

JD.CAST.SUSP.MUST is triggered when an object is checked with an instance of operator for type A and then cast to type B, where types A and B are unrelated. That is, Klocwork cannot find that A is a subtype of B, or that B is a subtype of A.

Vulnerability and risk

This is usually an error, because cast is not safe; the object can actually be another type than B. In some cases, this error can produce false positives when the path from instanceof to cast is incompatible.

Mitigation and prevention

Choose which type you actually want to use--A or B--and either change the typecast to A, or check the instanceof to B.

Vulnerable code example 1

1  public class Test {
2      void badCast(Object o) {
3          if (o instanceof String) {
4              Number n = (Number) o;
5              System.out.println("bad cast");
6          }
7      }
8  }

JD.CAST.SUSP.MUST is reported on line 4; the object is known because it is being checked with the 'instanceof <Type> construction.

Vulnerable code example 2

10   void setValue(Object a, Object value) {
11     if (a instanceof String) {
12       StringBuffer b = (StringBuffer) a;
13       b.append("=");
14       b.append(value);
15     }
16   }

JD.CAST.SUSP.MUST is reported for cast on line 12: Suspicious cast of 'a' from 'String' to 'StringBuffer', where types are unrelated.-> 11: a instanceof String-> 12: (StringBuffer)a.