Class Comparison via getName()
ID |
java.class_compare_with_getname |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:486, reliability, suspicious-comparison |
Description
Reports patterns like obj.getClass().getName().equals("ClassName") where class identity is compared by string name instead of using instanceof or .class comparison.
Rationale
Comparing classes by name is fragile: it breaks when the class is renamed, when multiple class loaders are involved (each loader defines its own namespace), or when obfuscation is applied. The comparison also cannot benefit from the compiler’s type checking:
// Bad: string-based class comparison
if (obj.getClass().getName().equals("com.example.MyClass")) {
process((MyClass) obj);
}