...
This noncompliant code example compares the name of the class of object auth
to the string "com.application.auth.DefaultAuthenticationHandler"
and branches on the result of the comparison.
Code Block | ||
---|---|---|
| ||
// Determine whether object auth has required/expected class object
if (auth.getClass().getName().equals(
"com.application.auth.DefaultAuthenticationHandler")) {
// ...
}
|
Comparing fully qualified class names is insufficient because distinct class loaders can load differing classes with identical fully qualified names into a single JVM.
Compliant Solution
This compliant solution compares the class object auth
to the class object for the canonical default authentication handler.
Code Block | ||
---|---|---|
| ||
// Determine whether object auth has required/expected class name if (auth.getClass() == com.application.auth.DefaultAuthenticationHandler.class) { // ... } |
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")) {
// ...
}
|
The call to This solution invokes loadClass()
returns 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 is correctly performed 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
This noncompliant code example compares the names of the class objects of x
and y
using the equals()
method. Again, it is possible that x
and y
are distinct classes with the same name if they come from different class loaders.
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.
Code Block | ||
---|---|---|
| ||
// Determine whether objects x and y have the same class
if (x.getClass() == y.getClass()) {
// Objects have the same class
}
|
...
Internals of Java Class Loading | |
Twelve rules for Developing More Secure Java Code | |
04. Object Orientation (OBJ) OBJ10-J. Do not use public static nonfinal variables