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.)
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With