My Java classes represent entities inside a database, and I find it practical to override the equals
method of my classes to make comparisons by id. So for example in my Transaction
class I have this piece of code
@Override
public boolean equals(Object other){
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Transaction))return false;
Transaction otherTrans = (Transaction) other;
if (id == null || otherTrans.id == null) return false;
return id.equals(otherTrans.id);
}
Now it seems a bit ugly to me that every class holds the same piece of code, with only the name of the class changed. I thought about making my classes extend a superclass MyEntity
where I would write the above method, replacing instanceof Transaction
with something like instanceof this.getClass()
, but this doesn't seem to be possible. I also thought about replacing it with instanceof MyEntity
, but that means two object could be considered equal even if they belonged to different classes, as long as they have the same id.
Is there any other way?