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?