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?
You can use the dynamic version of the instanceof
operator, which is Class
's isInstance
method.
Determines if the specified Object is assignment-compatible with the object represented by this Class.
if (!(getClass().isInstance(other))) return false;
This will not prevent an instance of a subclass from testing equals
on a superclass object, but a dynamic way of ensuring that it's the exact same class would be to compare the two Class
objects for equality.
if (!(getClass().equals(other.getClass()))) return false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With