Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See if two object have the same type

Let's say that I have a class A, and that B,C,D are derived from A.
If I want to know what's the type of an object referenced, I can declare:

// pseudo-code if(obj instanceof B)     < is B> else if(obj instanceof C)     < is C> else     <is D> 

This because I am sure that the classes derived from A are only B,C and D.
But what if I want just to check that two references point to the same kind of object?
So something like:

if(obj1 instanceof obj2)    <do something> 

But of course the syntax is wrong.How to check this without one thousand if-else?

like image 617
Ramy Al Zuhouri Avatar asked Apr 15 '12 14:04

Ramy Al Zuhouri


People also ask

How can you tell if two objects have the same class?

Difference Between == Operator and equals() Method Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.

How do you check if two objects are of the same type in Java?

If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal. Finally, equals() compares the objects' fields.

How do you check if two objects are identical in Python?

Every object has an identity, a type and a value. == and is are two ways to compare objects in Python. == compares 2 objects for equality, and is compares 2 objects for identity.


1 Answers

You mean something like

obj1.getClass().equals(obj2.getClass()) 

This should return true just if both obj1 and obj2 are of the same specific class.

But this won't work if you are comparing A with B extends A. If you want equality that returns true even if one is a subtype of another you will have to write a more powerful comparison function. I think that you can do it by looping with getSuperClass() to go up the hierarchy tree.

I think a simple solution can be also to do A.getClass().isAssignableFrom(B.getClass()), assuming that B extends A.

like image 162
Jack Avatar answered Sep 17 '22 17:09

Jack