Comparing two classes by its types or class names



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)

Answer

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.



Source: stackoverflow