Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an object is of the same class as this?

I have a base class for multiple data object types in Java. I want to create an equals method in the base class, that works directly when inherited.

Equality is determined by the two objects

  1. belonging to subclasses of the base class. This is easily achievable using

    if (!(anObject instanceof BaseClass))
        return false;
    
  2. having the same ID. The ID field is defined by the base class so we can here test that.

    if (this.id != ((BaseClass) anObject).id)
        return false;
    
  3. belonging to the same class. This is where I have the problem. Two objects may be of different types (and so be in different lists), but have the same ID. I have to be able to distinguish them. How can I do this?

like image 748
PurkkaKoodari Avatar asked Oct 21 '25 16:10

PurkkaKoodari


1 Answers

Use

this.getClass() == anotherObject.getClass()

instead of instanceof. This will return true only if the two object belong to the same class (it's safe to check if class objects are equal by reference). And after that you may compare the id.

like image 193
user2660000 Avatar answered Oct 23 '25 07:10

user2660000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!