Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Class objects

Tags:

java

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!

like image 227
reto Avatar asked Apr 15 '10 16:04

reto


People also ask

How do you compare object classes?

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)

Can you compare two objects of the same class?

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.

How do you compare objects in C++?

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

Can we compare 2 objects?

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.


2 Answers

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

like image 136
robinst Avatar answered Oct 02 '22 07:10

robinst


I am not sure if this will work for your specific situation, but you could try Class.isAssignableFrom(Class).

KlassA.class.isAssignableFrom(klass) 
like image 31
jt. Avatar answered Oct 02 '22 07:10

jt.