What are the pitfalls of comparing Class instances using the equality operator?
boolean compareTypes(Class<?> clazz, Class<?> rootClazz) {
return clazz == rootClazz;
}
No pitfalls really; it behaves just as you'd expect, if you expect the actual behavior :) Besides, the equals()
method for Class
objects is just the inherited one from Object
, which uses the ==
operator anyway.
The only surprising part is if the same class file is loaded by two different class loaders, you'll get two separate class objects which will compare as false
. This is by design.
If the classes were loaded by different ClassLoader
s then the classes may be from the same file, but not represented by the same object. In this situation, they may also have different behaviour, as one of the loaders may have performed bytecode modifications.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With