Carven Carven - 2 months ago 7
Java Question

Comparing Class Types in Java

I want to compare the class type in Java.

I thought I could do this:

class MyObject_1 {}
class MyObject_2 extends MyObject_1 {}

public boolean function(MyObject_1 obj) {
if(obj.getClass() == MyObject_2.class) System.out.println("true");
}


I wanted to compare in case if the obj passed into the function was extended from MyObject_1 or not.
But this doesn't work. It seems like the getClass() method and the .class gives different type of information.

How can I compare two class type, without having to create another dummy object just to compare the class type?

Answer

Try this:

MyObject obj = new MyObject();
if(obj instanceof MyObject){System.out.println("true");} //true

Because of inheritance this is valid for interfaces, too:

class Animal {}
class Dog extends Animal {}    

Dog obj = new Dog();
Animal animal = new Dog();
if(obj instanceof Animal){System.out.println("true");} //true
if(animal instanceof Animal){System.out.println("true");} //true
if(animal instanceof Dog){System.out.println("true");} //true

For further reading on instanceof: http://mindprod.com/jgloss/instanceof.html

Comments