Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.equals() or == when comparing the class of an object

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))
like image 625
Tim Mcneal Avatar asked Sep 26 '22 08:09

Tim Mcneal


2 Answers

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

like image 162
Francisco Hernandez Avatar answered Sep 30 '22 08:09

Francisco Hernandez


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

like image 37
hotzst Avatar answered Sep 30 '22 07:09

hotzst