Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two classes by its types or class names

Tags:

java

oop

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) 
like image 405
J.Olufsen Avatar asked May 05 '12 19:05

J.Olufsen


People also ask

How do you compare two classes?

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.

Can you compare two objects of the same class?

This can occur through simple assignment, as shown in the following example. Value equality means that two objects contain the same value or values. For primitive value types such as int or bool, tests for value equality are straightforward.

Can we compare two methods in Java?

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.


1 Answers

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()) 
like image 186
Bohemian Avatar answered Sep 21 '22 04:09

Bohemian