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 instanceof
, I don't have an object, I just have the Class
object. I (mis)use it like an enum in this situation!
The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)
This can occur through simple assignment, as shown in the following example. Value equality means that two objects contain the same value or values. For primitive value types such as int or bool, tests for value equality are straightforward.
Compare two objects in C++ We can determine whether two objects are the same by implementing a comparison operator== for the class. For instance, the following code compares two objects of class Node based on the value of x and y field. That's all about comparing two objects in C++.
Even though two different objects can have the same properties with equal values, they are not considered equal when compared using either the loose or strict equality operators ( == or === ). This is because arrays and objects in JavaScript are compared by reference.
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).
I am not sure if this will work for your specific situation, but you could try Class.isAssignableFrom(Class).
KlassA.class.isAssignableFrom(klass)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With