Instanceof Before Cast
ID |
java.instanceof_before_cast |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:704, reliability |
Description
Reports casts to reference types that are not guarded by a preceding instanceof check. Without such a guard, the cast throws ClassCastException at runtime if the expression does not hold a compatible type.
Rationale
When an Object reference is cast to a specific type without first verifying its actual runtime type via instanceof, the cast may fail unexpectedly:
Object o = getElement();
Button b = (Button) o; // ClassCastException if o is not a Button
This is a common source of runtime errors, especially when dealing with heterogeneous collections, deserialized objects, or framework callbacks that pass Object references.
Remediation
Always guard a reference-type cast with an instanceof check:
Object o = getElement();
if (o instanceof Button) {
Button b = (Button) o; // Safe: type verified
b.click();
}
Primitive casts (e.g. (int) doubleValue) are not affected by this rule since they never throw ClassCastException.