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))
You can use instanceof
for that kind of comparison too. The Class
implementation doesn't override equals
so comparing using ==
is correct i.e. it will check the runtime class. For example, this code will shows true:
public static void main(String[] args) {
Object object = "";
if (object.getClass() == String.class) {
System.out.println("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 ==
.
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 with equals
).
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
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