Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two Classes using the equality operator

Tags:

java

What are the pitfalls of comparing Class instances using the equality operator?

boolean compareTypes(Class<?> clazz, Class<?> rootClazz) {
    return clazz == rootClazz;
}
like image 237
auser Avatar asked Jul 25 '12 10:07

auser


2 Answers

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.

like image 169
Ernest Friedman-Hill Avatar answered Sep 22 '22 06:09

Ernest Friedman-Hill


If the classes were loaded by different ClassLoaders 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.

like image 20
OrangeDog Avatar answered Sep 18 '22 06:09

OrangeDog