Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use instanceof without knowing the type

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?

like image 232
splinter123 Avatar asked Feb 08 '16 22:02

splinter123


1 Answers

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;
like image 196
rgettman Avatar answered Sep 30 '22 00:09

rgettman