JD.CAST.DOWNCAST

Possible ClassCastException for subtypes

JD.CAST.DOWNCAST is triggered when an object of type B is cast to type C, where B and C are sub types of Object A.

Vulnerability and risk

This can cause a ClassCastException because a base class can have multiple child classes.

Vulnerable code example 1

Copy
  class TestVar {}
  class TestVar1 extends TestVar {
   TestVar display() {
       return new TestVar1();
   }
  }
  class TestVar2 extends TestVar {
   TestVar display() {
       return new TestVar2();
   }
  } 
  public class DownCast {
   public void cast() {
       TestVar var = new TestVar1();
       TestVar2 var2 = (TestVar2)var.display();       
   }
  }

Klocwork reports a JD.CAST.DOWNCAST defect at line 24, indicating, "TestVar2 var2 = (TestVar2)var.display(): Suspicious cast of 'TestVar1' to 'TestVar2', where 'TestVar2' is a subtype of 'TestVar'. This Object can hold other subtypes as well which can cause a ClassCastException."

Fixed code example 1

Copy
  class TestVar {}
  class TestVar1 extends TestVar {
   TestVar display() {
       return new TestVar1();
   }
  }
  class TestVar2 extends TestVar {
   TestVar display() {
       return new TestVar2();
   }
  } 
  public class DownCast {
   public void cast() {
       TestVar var = new TestVar1();
       TestVar var2 = var.display();
       if (var2 instanceOf TestVar2){
         TestVar2 testVar2 = (TestVar2)var2;
       }          
   }
  }

In this example, Klocwork no longer reports a defect because we check the Object with InstanceOf on line 25: if (var2 instanceOf TestVar2), and after that we type cast the object on line 26: TestVar2 testVar2 = (TestVar2)v2;.

Vulnerable code example 2

Copy
  class TestVar {
   TestVar display() {
       return new TestVar();
   }
  }
  class TestVar1 extends TestVar {
   TestVar display() {
       return new TestVar1();
   }
  }
  public class DownCast {
   public void cast() {
       TestVar var = new TestVar();
       TestVar1 var1 = (TestVar1) var.display();
   }
  }

Klocwork reports a JD.CAST.DOWNCAST defect at line 23, indicating, "TestVar1 var1 = (TestVar1)var.display(): Suspicious cast of 'TestVar' to 'TestVar1', where 'TestVar1' is subtype of 'TestVar'. This Object can hold other subtypes as well which can cause ClassCastException."

Fixed code example 2

Copy
  class TestVar {
   TestVar display() {
       return new TestVar();
   }
  }
  class TestVar1 extends TestVar {
   TestVar display() {
       return new TestVar1();
   }
  }
  public class DownCast {
   public void cast() {
       TestVar var = new TestVar();
       TestVar var1 = var.display();
       if (var1 instanceOf TestVar1){
         TestVar1 testVar1 = (TestVar1)var1;
       }
   }
  }

In this example, Klocwork no longer reports a defect because we check the Object with InstanceOf on line 24: if (var1 instanceOf TestVar1), and after that we type cast the object on line 25: TestVar1 testVar1 = (TestVar1)var1;.

Related checkers