How do I know if I reached an Object in a super.equals call chain?

I have a problem with Class.getSuperclass (). I want to create a class hierarchy, where each child, comparing their attributes with another class, will pass the request to the equal parent element. With this approach, I need to end the call to super.equals when I have reached a level higher than Object, since Object performs an isSame comparison, and this 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 pseudo call myImmediateSuperIsObject. How to write this? When Parent.equals is called from Child.equals, then inside Parent this.getClass (). GetSuperclass () is not an Object, but a Parent. This is because when we call getSuperclass (), we always start with the instance class, which is a child. Therefore, I can build the entire hierarchy by recursively calling getSuperclass until I get zero, but how do I determine if I am just above the object in my equal call chain?

I repeat, all this is only a problem, because I need to generate a class hierarchy. If I wrote this manually, I would certainly know that I am expanding the object and stop calling super.equals ().

Any idea?

Regards, Dietrich

+4
source share
2 answers

Since you are comparing properties in a hierarchy of objects, have you considered EqualsBuilder.reflectionEquals from Commons Lang ?

+1
source

You can use getClass (). getSuperClass () and then check if its Object.class

Example:

 class Animal { boolean myImmediateSuperIsObject() { System.out.println("I am " + getClass() + " and my parent is " + getClass().getSuperclass()); return this.getClass().getSuperclass() == Object.class; } } class Horse extends Animal { boolean myImmediateSuperIsObject() { System.out.println("I am " + getClass() + " and my parent is " + getClass().getSuperclass()); return this.getClass().getSuperclass() == Object.class; } } new Horse().myImmediateSuperIsObject(); new Animal().myImmediateSuperIsObject(); 
+1
source

Source: https://habr.com/ru/post/1436306/


All Articles