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.
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{}
You can also use to reflect mostly Class.isInstance.
Class.isInstance
Class<?> stringClass = Class.forName("java.lang.String"); assert stringClass.isInstance("Some string");
, , instanceof - .
instanceof
instanceof : 1) , , /, . 2) null, null instanceof Class false
, , .
, , , instanceof Class, , .
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.
isAssignableFrom