I have a problem with Class.getSuperclass(). I want to generate a hierarchy of classes where each child, after comparing its attributes to the other class, passes on the equals request to the parent. With this approach I need to stop calling super.equals when I have reached the level above Object since Object does an isSame comparison and that is not what I want.
Suppose I have this hierarchy:
class Child extends Parent {
...
public boolean equals(Object other) {
... compare my attributes to other, if everything matches:
if (myImmediateSuperIsObject()) {
return true;
} else {
return super.equals(other)
}
}
}
class Parent extends Object {
public boolean equals(Object other) {
... compare my attributes to other, if everything matches:
if (myImmediateSuperIsObject()) {
return true;
} else {
return super.equals(other)
}
}
}
The problem is the myImmediateSuperIsObject pseudo call. How to write it?
When Parent.equals is called from Child.equals, then within Parent, this.getClass().getSuperclass() is not Object, but Parent. That is because when calling getSuperclass(), we are always starting at the class of the instance, which is Child. So I can build the entire hierarchy by recursively calling getSuperclass until I get null, but how do I determine if I’m just above Object in my chain of equals calls?
To reiterate, all this is only an issue because I need to generate the class hierarchy. If I were to write this manually, I would of course know that I am extending object and stop calling super.equals().
Any idea?
Best regards,
Dietrich
Since you’re comparing properties in your object hierarchy, have you considered using EqualsBuilder.reflectionEquals from Commons Lang?