问题
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))
回答1:
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 ==.
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/33465243/equals-or-when-comparing-the-class-of-an-object