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

2020-04-10 02:37发布

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

3条回答
男人必须洒脱
2楼-- · 2020-04-10 03:16

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 a String object.

查看更多
一纸荒年 Trace。
3楼-- · 2020-04-10 03:17

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

查看更多
孤傲高冷的网名
4楼-- · 2020-04-10 03:25

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:

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

查看更多
登录 后发表回答