35

There is need to compare two objects based on class they implement? When to compare using getClass() and when getClass().getName()? Is there any difference between this approaches to compare two Objects class types (names)?

public abstract class Monster { ... }
public class MonsterTypeOne extends Monster { ... }
public class MonsterTypeTwo extends  Monster { ... }

    Monster monster = MonsterTypeOne();
    Monster nextMonster = MonsterTypeTwo();


if(nextMonster.getClass().getName().equals(monster.getClass().getName()) )// #1

if(nextMonster.getClass().equals(monster.getClass()) )// #2

EDIT 1


What about: ?

nextMonster.getClass().equals(MonsterTypeOne.class)
2
  • Do you need .equals with getClass? Get class returns a non-String object I believe. +1 interesting question. Commented May 5, 2012 at 19:31
  • If you use a good OOP structure, you should be able to deal with this through inheritance and composition. Unless you're writing meta-code (code that deals with Java itself) I've not found a reason to even use "instanceof" in my career.
    – NomadMaker
    Commented Apr 17, 2020 at 15:24

8 Answers 8

36

Use class.equals():

if (nextMonster.getClass().equals(monster.getClass()))

or, because each class is like a singleton - there's only one instance of each Class per class loader, and most JVMs only have the one class loader - you can even use an identity comparison:

if (nextMonster.getClass() == monster.getClass())
1
  • 1
    Once instance per JVM or per class loader?
    – Mark
    Commented Nov 15, 2018 at 0:50
23

Is there any difference between this approaches to compare two Objects class types (names)?

Yes. Two classes may have the same name if they are loaded by different ClassLoaders.

"The basics of Java class loaders" says

At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name.

"Eclipse - a tale of two VMs (and many classloaders)" says

That means it's possible to have two classes with the same name loaded into a VM at once, provided that they have two separate ClassLoaders


When to compare using getClass() and when getClass().getName()?

If you want to know whether two objects are of the same type you should use the equals method to compare the two classes -- the first option.

I can't imagine why you'd want to do this, but if you want to know whether two objects with different concrete types have types with the same fully qualified name, then you could use the second. If you don't understand "concrete types" and "fully qualified names" in the context of Java then you're not writing type analysis code for java so you don't want to.

4

I ran into a problem comparing two classes using .equals. The above provided solution is not entirely accurate. Class does not implement Comparable.

Class references are not necessarily true singletons within a JVM because you can have multiple ClassLoaders.

I was writing a Maven plugin that was digging annotations out of beans after compile. The plugin had one classloader and I had my own classloader. When comparing two classes of the same name from different loaders the comparison would fail.

The implementation of Object.equals looks like this:

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

So you will be comparing references.

If you are comparing classes and you know for sure there will only be one classloader involved you can safely use .equals or c1 == c2 but if you are not sure you should compare by name:

if(c1.getName().equals(c2.getName()) {
   ...
}
2
  • why would you need to compare classnames from two differnt classloaders? Is that a valid senario? Give me an example when you need to do that in real life. Commented Mar 29, 2016 at 21:42
  • My application was very unusual. I was making a Maven plugin that generates documentation for REST endpoints. I wanted to use the JAX annotations (or Spring) to generate HTML docs. The Maven plugin used would load all the classes using the JarClassLoader class and the Maven plugin ran its code in the build's classloader. I was trying to see if the annotation was present in the Jar's class but the comparison failed even though they were the same class names. I ended up abandoning the project. Commented Mar 30, 2016 at 23:39
1

As a matter of fact comparing trusted class by name is a weakness. Refer https://cwe.mitre.org/data/definitions/486.html

if (nextMonster.getClass() == monster.getClass())

is the correct way to compare classes

if (nextMonster.getClass().equals(monster.getClass()))

should still work for the same reason @Bohemian mentioned

0

Another way to achieve the same will be by overriding hashcode in subclass.

public interface Parent {
}

public static class Child1 implements Parent{
    private String anyfield="child1";

    @Override
    public int hashCode() {
        //Code based on "anyfield"
    }

    @Override
    public boolean equals(Object obj) {
        //equals based on "anyfield"
    }
}

public static class Child2 implements Parent{
    private String anyfield="child2";

    @Override
    public int hashCode() {
        //Code based on "anyfield"
    }

    @Override
    public boolean equals(Object obj) {
        //equals based on "anyfield"
    }
}

Now the equals will return if implementations/subclasses are of same concrete type.

public static void main(String args[]){
    Parent p1=new Child1();
    Parent p2=new Child1();
    Parent p3=new Child2();
    System.out.println("p1 and p2 are same : "+p1.equals(p2));
    System.out.println("p2 and p3 are same : "+p2.equals(p3));
}

Output-

p1 and p2 are same : true
p2 and p3 are same : false
1
  • This does not attempt to answer the question. OP is asking on how to check equality of classes, i.e. are two Class-Objects equal. Not if two subclasses of a parent are equal...
    – Lino
    Commented Jun 16, 2021 at 9:58
0

You can use the inbuilt method of Class :

if(nextMonster.getClass().isAssignableFrom(monster.getClass()))
1
  • not sure why this solution didn't get enough recognition Commented Apr 19, 2023 at 16:00
0

The answer by @Mike Samuel worked for me in Android Studio setting. A slight variation is that when passing the class-name, which in my case was an Activity, that name must have the extension .class. If this approach is used, then equals() works well.

if (passedActivityName.equals(KnownActivity.class)){
    //matches
    //note: passedActivityName was given fully as passedActivityName.class 
}

I hope this helps somehow although not strictly related.

-1

if you have an array use getClass().getComponentType() to compare its content type

jshell> var array1 = new int[15]
array1 ==> int[15] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

jshell> var array2 = new int[10]
array2 ==> int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

jshell> array1.getClass() == array2.getClass()
$7 ==> true

jshell> array1.getClass().getComponentType()
$8 ==> int

jshell> array1.getClass().getComponentType() == int.class
$12 ==> true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.