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?
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.
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.
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.
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
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:
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