Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 763
Carven Avatar asked May 27 '11 08:05

Carven


People also ask

How do you compare types of classes in Java?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.

How do you compare objects with different classes?

If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal. Finally, equals() compares the objects' fields.

Can we compare two methods in Java?

Java String compareTo() MethodThe compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.


2 Answers

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

like image 111
Thor Avatar answered Sep 22 '22 00:09

Thor


If you don't want to or can't use instanceof, then compare with equals:

 if(obj.getClass().equals(MyObject.class)) System.out.println("true"); 

BTW - it's strange because the two Class instances in your statement really should be the same, at least in your example code. They may be different if:

  • the classes have the same short name but are defined in different packages
  • the classes have the same full name but are loaded by different classloaders.
like image 32
Andreas Dolk Avatar answered Sep 23 '22 00:09

Andreas Dolk