reto reto - 1 year ago 76
Java Question

Compare class objects

I have to compare a class object against a list of pre defined classes. Is it safe to use == or should I use equals()?

if (klass == KlassA.class) {
} else if (klass == KlassB.class) {
} else if (klass == KlassC.class) {
} else {

Note: I cannot use
, I don't have an object, I just have the
object. I (mis)use it like an enum in this situation!

Answer Source

java.lang.Class does not override the equals method from java.lang.Object, which is implemented like this:

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

So a == b is the same as a.equals(b) (except if a is null).