In java, when you are testing what the object's class is equal to would you use .equals() or ==
For example in the code below would it be:
if(object.getClass() == MyClass.class)
or
if(object.getClass().equals(MyClass.class))
In java, when you are testing what the object's class is equal to would you use .equals() or ==
For example in the code below would it be:
if(object.getClass() == MyClass.class)
or
if(object.getClass().equals(MyClass.class))
Well, I suggest you to read the J.Bloch's book Effective Java.
As a common rule, you should always tend to use
.equals()
method of a class unless you want to explicitly compare the pointers of given instances. That is, you want to compare what the class represents, like class of an instance in your examples, or, for example, content of a string but not the pointer to aString
object.I personally tend to use the
==
for classes as I think it is slightly more performant. However you have to be aware, that this returns only true if the reference to the object is the same and not only the content (like withequals
).For example comparison of two
Class
instances with==
will return false, if the two instances where loaded by different ClassLoaders.To be on the save side, you should probably use
equals
You can use instanceof for that kind of comparision too, anyway, The Class implementation don´t override equals so comparing using == is correct, it will check the runtime class, f.e: this code will shows true:
the general rule for comparing objects is use 'equals', but for comparing classes if you don´t want to use instanceof, i think the correct way is to use ==.