7

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.)

Community
  • 1
  • 1
Adrian Smith
  • 17,236
  • 11
  • 71
  • 93

2 Answers2

7

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
5

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.

John Feminella
  • 303,634
  • 46
  • 339
  • 357