JD.CAST.COL.MUST
ClassCastException for collection
JD.CAST.COL.MUST occurs when none of the types used to store values in collections is related to the type used in an immediate cast.
Vulnerability and risk
This usually causes a ClassCastException, because objects in the collection have different types.
Vulnerable code example 1
public class Test {
protected static final String NAME = "name";
protected static final String ADDRESS = "address";
private static final Map<String, Object> map = new HashMap<String, Object>();
public void setInfo(String name, String addr) {
map.put(ADDRESS, addr);
map.put(NAME, name);
}
public static getInfo() {
Test test = new Test();
test.setInfo("me", “Delhi”);
System.out.println("Address==>"+(String)map.get(ADDRESS));
System.out.println("Name==>"+(Number)map.get(NAME));
}
}
Klocwork reports a JD.CAST.COL.MUST defect at line 22, indicating: "Suspicious cast to ‘java.lang.Number of collection element. Object was put into the collection as ‘java.lang.String’.-> 16: map.put(NAME, name); -> 21: System.out.println("Name==>"+(Number)map.get(NAME));".
Fixed code example 1
public class Test {
protected static final String NAME = "name";
protected static final String ADDRESS = "address";
private static final Map<String, Object> map = new HashMap<String, Object>();
public void setInfo(String name, String addr) {
map.put(ADDRESS, addr);
map.put(NAME, name);
}
public static getInfo() {
Test test = new Test();
test.setInfo("me", “Delhi”);
System.out.println("Address==>"+(String)map.get(ADDRESS));
System.out.println("Name==>"+(String)map.get(NAME));
}
}
Klocwork no longer reports a defect, since the objects are of the same type.
Vulnerable code example 2
public class Test {
ArrayList<Object> list = new ArrayList<Object>();
public void setInfo() {
list.add("name");
list.add(“address”);
}
public void display() {
System.out.println("name==>"+(String) list.get(0));
System.out.println("name==>"+(Number) list.get(1));
}
}
Klocwork reports a JD.CAST.COL.MUST defect at line 9, indicating: "Suspicious cast to ‘java.lang.Number’ of collection element. Object was put into the collection as ‘java.lang.String’. ->4: list.add("address"); -> 9: System.out.println("name==>"+(Number) list.get(1));".
Fixed code example 2
public class Test {
ArrayList<Object> list = new ArrayList<Object>();
public void setInfo() {
list.add("might");
list.add("must");
}
public void display() {
Test test = new Test();
test.setInfo();
for(Object obj : list) {
if(obj instanceof String) {
System.out.println("name==>"+(String) obj);
}
}
}
}
Klocwork no longer reports a defect, since the objects are of the same type.