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.
The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection.
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
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{}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With