Comparing two classes by its types or class names

前端 未结 7 1085
耶瑟儿~
耶瑟儿~ 2021-02-01 15:34

There is need to compare two objects based on class they implement? When to compare using getClass() and when getClass().getName()? Is there any differ

7条回答
  •  梦毁少年i
    2021-02-01 16:01

    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())
    

提交回复
热议问题