1

Should I test equality between two class type objects using the == operator or using a more reliable way like Object.equals(Object)

Example

String.class == obj.getClass() or String.class.equals(obj.getClass())

PS: I'm only interested in using class type comparison (not using the instanceof operator)

marsouf
  • 1,107
  • 8
  • 15
  • 1
    https://stackoverflow.com/questions/5997801/java-comparing-classes-with-or-equals-is-there-a-difference & https://stackoverflow.com/questions/3738919/does-java-guarantee-that-object-getclass-object-getclass – Alexis C. Jan 25 '18 at 12:39

2 Answers2

1

No, as long as you don't have different classloaders in the JVM. Each object in java has a corresponding java.lang.Class object and its loaded into JVM once regardless the number of actual instances of the object.

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
1

Both versions are basically equal since java.lang.Class uses the standard implementation inside Object:

public boolean equals(Object obj) {
    return (this == obj);
}

And since Class is final you can't override that.

Note, however, that once you're working with different classloaders you might get two classes that are basically the same but different instances, i.e. java.lang.String != java.lang.String if both come from different classloaders (that particular example probably won't happen, it's just an illustration).

As a final note, you might want to use equals() anyways if the instance you're calling it on can never be null (and String.class won't be null). That way you're reinforcing the habit to use equals() over == and in the extremely unlikely case that Class will change its implementation of equals() at some point it's probably safer to use it right now.

Thomas
  • 87,414
  • 12
  • 119
  • 157