tags:

views:

459

answers:

4

I remember reading in some Java book about any operator other than 'instanceof' for comparing the type hierarchy between two objects.

instanceof is the most used and common. I am not able to recall clearly whether there is indeed another way of doing that or not.

+6  A: 

You can also, for reflection mostly, use Class.isInstance.

Class<?> stringClass = Class.forName("java.lang.String");
assert stringClass.isInstance("Some string");

Obviously, if the type of the class is known at compile-time, then instanceof is still the best option.

Chris Jester-Young
I don't think this will t work if you're trying to compare a subclass to a parent class...
Stephane Grenier
But I think that's true for almost all the answers here...
Stephane Grenier
+3  A: 

The instanceof operation is the best option for two reasons: 1) It handles subtyping, so if you have an instance of a subclass/subtype you would still get true. 2) It handles null, so null instanceof Class would return false

If you take an object's class and then compare to another class, you're risking taking the class of a null object, and you can't directly get subtyping.

If you work with objects that represent classes, you can use the reflection operations, since instanceof would refer to their own class, Class, rather than to the class they represent.

Uri
Best for what application? instanceof is generally incorrect for equals implementation in non-final classes.
erickson
erickson, you mean it will return true for subclasses as well. right? But there we most likely start with checking null. So, using getClass() for both reasons make sense in that case.
Adeel Ansari
+4  A: 

Yes, there is. Is not an operator but a method on the Class class.

Here it is: isIntance(Object o )

Quote from the doc:

...This method is the dynamic equivalent of the Java language instanceof operator

public class Some {
    public static void main( String [] args ) {
        if ( Some.class.isInstance( new SubClass() ) ) {
            System.out.println( "ieap" );
        } else { 
            System.out.println( "noup" );
        }
    }
}
class SubClass extends Some{}
OscarRyz
Thanks Oscar. Actually this is what I was searching for.
Tushu
+1  A: 
if ( someClass.isAssignableFrom( obj.getClass() ) )

is equivalent to

if ( obj instanceof Foo )

Use instanceof if the class to be checked against is known at compile time, use isAssignableFrom if it is only known at runtime.

Adrian
We can use instanceof in both cases. Why not?
Adeel Ansari
I have always for isAssignableFrom a confusing method name; I have to mentally reverse it to obj.getClass() is assignable to someClass.
Software Monkey
I think its a very good way to use isAssignableFrom() method before doing a casting.
Tushu