org.sonar.l10n.java.rules.squid.S1872.html Maven / Gradle / Ivy
The newest version!
There is no requirement that class names be unique, only that they be unique within a package. Therefore trying to determine an object's type based on its class name is an exercise fraught with danger. One of those dangers is that a malicious user will send objects of the same name as the trusted class and thereby gain trusted access.
Instead, the instanceof
operator should be used to check the object's underlying type.
Noncompliant Code Example
package computer;
class Pear extends Laptop { ... }
package food;
class Pear extends Fruit { ... }
class Store {
public boolean hasSellByDate(Object item) {
if ("Pear".equals(item.getClass().getSimpleName())) { // Noncompliant
return true; // Results in throwing away week-old computers
}
}
}
Compliant Solution
class Store {
public boolean hasSellByDate(Object item) {
if (item instanceof food.Pear) {
return true;
}
}
}
See
- MITRE, CWE-486 - Comparison of Classes by Name
© 2015 - 2025 Weber Informatics LLC | Privacy Policy