views:

54

answers:

2

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?

+9  A: 

Don't bother with the fully qualified class names - just compare class references:

public boolean foo(Object o1, Object o2) {
    return o1.getClass() == o2.getClass();
}

Classes are essentially unique by name and classloader - so this will return false if the objects are of the same class name but loaded by different classloaders, but that's probably appropriate: they could be completely different classes in all but name! If the classes have the same name and classloader, however, they'll have the same reference.

Note that this will throw a NullPointerException if either o1 or o2 is null, but again that's probably what you want.

Jon Skeet
Thank you for answering my question Jon...
Ingmar
A: 

Can you qualify rather slow? Compared to what? Also please elaborate your usage scenario? In java the Object api includes a equals/hashCode method paring that should be used to identify equality between objects. It appears as if this is what you may be attempting to find, ie:

new Integer(4).equals(new Integer(5))

In this case, the best implementation for overriding equals in SomeClass is as follows:

public boolean equals(Object obj) {
    if (obj instanceof SomeClass) {
        return ((SomeClass) obj).identityField.equals(identityField);
    }
    return false;
}
public int hashCode() {
    return 31 * identity.hashCode();
}

Making sure you provide an identity within your object.

Raymond