Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

JD.CAST.COL

JD.CAST.COL is found when an object is retrieved from a collection (map or list) and is cast immediately as type A, although it was put into the collection as type B, where types A and B are unrelated. That is, Klocwork cannot find that A is a subtype of B or B is a subtype of A. The JD.CAST.COL checker checks only class fields.

Vulnerability and risk

This usually causes a ClassCastException, because objects in the collection have different types.

Mitigation and prevention

Choose which type you actually want to use--A or B--and, either put objects of type A, or get objects of type B. The other option is to allow both of these types to use an instanceof check before casting the object.

Example 1

10 public class JD_CAST_COL_Sample_1 {
11     HashMap test;
12     void foo(){
13         test.put("a","b");
14         JD_CAST_COL_Sample_1 res =(JD_CAST_COL_Sample_1)test.get("a");
15     }
16 }

JD.CAST.COL is reported for line 14: Suspicious cast to 'com.klocwork.jdefects.checkers.ast.samples.JD_CAST_COL_Sample_1' of collection element. Object was put into the collection as 'java.lang.String'.-> 13: test.put(a, b)-> 14: (JD_CAST_COL_Sample_1)test.get(a)

Related checkers