...
The right-hand-side of the comparison directly names the class of the canonical authentication handler. In the event that the canonical authentication handler had not yet been loaded, the Java runtime manages the process of loading the class. Finally, the comparison is correctly performed on the two class objects.
Compliant Solution
This compliant solution compares the class object auth
to the class object that the current class loader loads, instead of comparing just the class names.
Code Block | ||
---|---|---|
| ||
// Determine whether object auth has required/expected class name
if (auth.getClass() == this.getClass().getClassLoader().loadClass(
"com.application.auth.DefaultAuthenticationHandler")) {
// ...
}
|
This solution invokes loadClass()
to find the class with the specified name in the current name space (consisting of the class name and the defining class loader), and correctly performs the comparison on the two class objects. We recommend that programmers use the previous compliant solution because it is simpler. Nevertheless, manual loading of the class object remains a compliant technique.
Noncompliant Code Example
...
Code Block | ||
---|---|---|
| ||
// Determine whether objects x and y have the same class name if (x.getClass().getName().equals(y.getClass().getName())) { // Objects have the same class } |
Compliant Solution
This compliant solution correctly compares the two objects' classes.
...