Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one compare java.lang.Class objects with == in Java? [duplicate]

Tags:

java

Possible Duplicate:
Does Java guarantee that Object.getClass() == Object.getClass()?

If I have a class such as

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

can I then do:

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

or do I have to do

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

In addition, further to knowing the answer, I would love to know a reference i.e. where this is defined.

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

like image 820
Adrian Smith Avatar asked Jan 17 '12 14:01

Adrian Smith


2 Answers

You can use == but you gain nothing because that's exactly what Class.equals() does.

Class doesn't define an equals method, so it inherits from Object. You can read the source to see this.

I use equals where possible as then I don't need to think about it. When I am reading code (including my code) I still don't need to ask myself is == the same as equals or not for this class.

like image 135
Peter Lawrey Avatar answered Nov 09 '22 01:11

Peter Lawrey


You can compare classes with ==, and that's the same thing as equals for the case of Class, but your example suggests that you want to know whether one class has an "is-a" relationship with another. Two classes are only equal if they're the same class, and clearly Vehicle.class != Car.class.

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

like image 41
John Feminella Avatar answered Nov 09 '22 03:11

John Feminella