Comparing two classes using the equality operator

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

boolean compareTypes(Class<?> clazz, Class<?> rootClazz) { return clazz == rootClazz; } 
+6
source share
5 answers

No pitfalls; it works the same as you would expect if you expect the actual behavior :) Also, the equals() method for Class objects is only inherited from Object , which in any case uses the == operator.

The only surprising part is that if the same class file is loaded by two different class loaders, you will get two separate class objects that will be compared as false . This is by design.

+12
source

If classes were loaded by different ClassLoader , then classes can be from the same file, but not represented by the same object. In this situation, they may also have different behavior, since one of the loaders can perform bytecode modifications.

+3
source

There are no pitfalls. Class does not override the default value of Object.equals , so it has the same semantics, except it will actually be a trap using equals , since the left null operand will cause NPE.

+1
source

The class does not override equals and does not extend Object directly; equals and == are the same in this case.

Regardless, it is best to use equals when you can.

If you do not know the difference between == and equal, read about it.

0
source

It may be wiser to do

 boolean compareTypes(Class<?> clazz, Class<?> rootClazz) { return clazz.getName().equals(rootClazz.getName()); } 

or some version of getName() such as getSimpleName()

-1
source

Source: https://habr.com/ru/post/921286/


All Articles