Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way other than instanceof operator for object type comparison in java?

Tags:

java

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.

like image 678
Tushu Avatar asked Dec 18 '08 05:12

Tushu


People also ask

What can be used instead of Instanceof in Java?

The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection.

Which operators compares an object to a specified type in Java?

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.

What is difference between getClass method and Instanceof operator?

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.

How do you check if an object is an instance of another object 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.


1 Answers

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{}
like image 187
OscarRyz Avatar answered Oct 04 '22 11:10

OscarRyz