Is it possible to compare java.lang.Class objects with == in Java?

Possible duplicate:
Is Java a guarantee that Object.getClass () == Object.getClass ()?

If I have a class like

Class<? extends MyObject> aClass = ...; 

can i do:

 if (aClass == MySubObject.class) { ... } 

or i need to do

 if (aClass.equals(MySubObject.class)) { ... } 

In addition, in addition to knowing the answer, I would like to know the link, that is, where it is defined.

I prefer to use == if possible, because I find it more readable and faster. (Obviously, this is not much readable or much faster, but still, why use a more complex solution if a simpler solution is available.)

+6
source share
2 answers

You can use == , but you get nothing, because that is exactly what Class.equals() does.

The class does not define the equals method, so it inherits from Object. You can read the source to see this.

I use equals where possible, since then I do not need to think about it. When I read the code (including my code), I still do not need to ask myself: == the same as equals or not for this class.

+7
source

You can compare classes with == , and the same as equals for the case of Class , but your example tells you that you want to know if one class has an is-a relationship with another. Two classes are equal if they are the same class and obviously Vehicle.class != Car.class .

If you want to know if there is a Car is-a Vehicle , use Class#isAssignableFrom .

+5
source

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


All Articles