Possible ClassCastException for different types

JD.CAST.SUSP.MIGHT 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 may be 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 may be an error, because cast is not safe; the object may 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

  public class Test {
      void mayBeBadCast(Object o) {
          if (!(o instanceof String)) {
              Number n = (Number) o;
              System.out.println("May be bad cast");

JD.CAST.SUSP.MIGHT is reported for line 4 because we are uncertain about the object type: potentially the type is not safe to be used in cast. Using the '! (a instanceof <Type>)' construction makes the type of 'a' uncertain.