Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if two Java objects are of the same class

I am attempting to do the equivalent of

if ( object1.class == object2.class ) {     //do something }   

which of course doesn't work, what method am I overlooking?

like image 733
ToothlessRebel Avatar asked Jul 25 '11 20:07

ToothlessRebel


People also ask

How do you check if an object is an instance of a class Java?

Java instanceof Operator The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

Can two objects have same reference in Java?

Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.

Can two objects have same reference?

No, it never returns true unless you feed it the same exact object reference. The reason for it is that Java objects are not "embedded" in one another: there is a reference to B inside A , but it refers to a completely different object.


1 Answers

If they're from the exact same class:

boolean result = object1.getClass().equals( object2.getClass()); 

Now if they are compatible classes (if one is of a descendent class to the other):

HashMap<String,Object> hashMap = new HashMap<String,Object>(); LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<String,Object>(); boolean result = hashMap.getClass().isAssignableFrom( linkedHashMap.getClass() ); 

As LinkedHashMap is a subclass of HashMap this result variable will be true, so this might probably be better for you as it's going to find exact and subclass matches.

Also, you should avoid using ".class" on variables, as it might not give you the correct result, example:

Object someText = "text value"; System.out.println( someText.class.getName() ); //this will print java.lang.Object and not java.lang.String 

When you're using ".class" you're acessing the variable static property and not the class of the object itself.

like image 193
Maurício Linhares Avatar answered Sep 21 '22 17:09

Maurício Linhares