Is there a way other than instanceof operator to compare object types in java?

I remember reading in a Java book some kind of statement other than "instanceof" to compare the type hierarchy between two objects.

instanceof is the most commonly used and common. I cannot clearly remember if there is another way to do this or not.

+5
source share
4 answers

Yes there is. This is not an operator, but a method of the Class class.

Here it is: isIntance (Object o)

Quote from the document:

... This method is the dynamic equivalent of a Java language instance statement

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{}
+6
source

You can also use to reflect mostly Class.isInstance.

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

, , instanceof - .

+6

instanceof : 1) , , /, . 2) null, null instanceof Class false

, , .

, , , instanceof Class, , .

+3
if ( someClass.isAssignableFrom( obj.getClass() ) )

equivalently

if ( obj instanceof Foo )

Use instanceofif the class you want to check is known at compile time, use isAssignableFromif it is known only at run time.

+1
source

All Articles