Comparing Class Types in Java

JavaTypesCompare

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

It prints true on my machine. And it should, otherwise nothing in Java would work as expected. (This is explained in the JLS: 4.3.4 When Reference Types Are the Same)

Do you have multiple classloaders in place?


Ah, and in response to this comment:

> I realise I have a typo in my > question. I should be like this: >

MyImplementedObject obj = new MyImplementedObject ();
if(obj.getClass() == MyObjectInterface.class) System.out.println("true");

> MyImplementedObject implements > MyObjectInterface So in other words, I > am comparing it with its implemented > objects.

OK, if you want to check that you can do either:

if(MyObjectInterface.class.isAssignableFrom(obj.getClass()))

or the much more concise

if(obj instanceof MyobjectInterface)

Solution 4 - Java

As said earlier, your code will work unless you have the same classes loaded on two different class loaders. This might happen in case you need multiple versions of the same class in memory at the same time, or you are doing some weird on the fly compilation stuff (as I am).

In this case, if you want to consider these as the same class (which might be reasonable depending on the case), you can match their names to compare them.

public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
  // TODO handle nulls maybe?
  return c1.getCanonicalName().equals(c2.getCanonicalName());
}

Keep in mind that this comparison will do just what it does: compare class names; I don't think you will be able to cast from one version of a class to the other, and before looking into reflection, you might want to make sure there's a good reason for your classloader mess.

Solution 5 - Java

Comparing an object with a class using instanceOf or ... is already answered.

If you have two objects and you want to compare their types with each other, you can use:

if (obj1.getClass() == obj2.getClass()) {
   // Both have the same type
}

Solution 6 - Java

If you had two Strings and compared them using == by calling the getClass() method on them, it would return true. What you get is a reference on the same object.

This is because they are both references on the same class object. This is true for all classes in a java application. Java only loads the class once, so you have only one instance of a given class at a given time.

String hello  = "Hello";
String world = "world";

if (hello.getClass() == world.getClass()) {
    System.out.println("true");
} // prints true

Solution 7 - Java

Hmmm... Keep in mind that Class may or may not implement equals() -- that is not required by the spec. For instance, HP Fortify will flag myClass.equals(myOtherClass).

Solution 8 - Java

Check Class.java source code for equals()

public boolean equals(Object obj) {
  return this == obj;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarvenView Question on Stackoverflow
Solution 1 - JavaThorView Answer on Stackoverflow
Solution 2 - JavaAndreas DolkView Answer on Stackoverflow
Solution 3 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 4 - JavadjjeckView Answer on Stackoverflow
Solution 5 - JavaMahdi-MalvView Answer on Stackoverflow
Solution 6 - JavaSamView Answer on Stackoverflow
Solution 7 - JavaMax TardiveauView Answer on Stackoverflow
Solution 8 - JavaLi TaoView Answer on Stackoverflow