How can I find out if two arguments are instances of the same, but unknown class?

Posted by Ingmar on Stack Overflow See other posts from Stack Overflow or by Ingmar
Published on 2010-04-17T14:35:53Z Indexed on 2010/04/17 14:43 UTC
Read the original article Hit count: 328

Filed under:
|
|
|

Let us say we have a method which accepts two arguments o1 and o2 of type Object and returns a boolean value. I want this method to return true only when the arguments are instances of the same class, e.g.:

foo(new Integer(4),new Integer(5));

Should return true, however:

foo(new SomeClass(), new SubtypeSomeClass());

should return false and also:

foo(new Integer(3),"zoo");

should return false.

I believe one way is to compare the fully qualified class names:

public boolean foo(Object o1, Object o2){
 Class<? extends Object> c1 = o1.getClass();
 Class<? extends Object> c2 = o2.getClass();
 if(c1.getName().equals(c2.getName()){ return true;}
 return false;  
}

An alternative conditional statement would be :

if (c1.isAssignableFrom(c2) && c2.isAssignableFrom(c1)){ return true; }

The latter alternative is rather slow. Are there other alternatives to this problem?

© Stack Overflow or respective owner

Related posts about java

Related posts about reflection