I have a class that extends to another class and that class extends to another class.
class 1 extends class 2
class 2 extends class 3
class 3 extends class 4
class 4 extends class 5
class 5 extends class 6
Now I want to find all super classes of class 1.
Anyone know how I could do that in java?
You can use
getSuperclass()
up to theObject
.But read the doc first to understand what it returns in the case of interfaces etc. There are more methods to play with on the same page.
As a variation, with a tight loop, you can use a
for
loop instead:The other answers are right about using
Class.getSuperclass()
. But you have to do it repeatedly. Something likeUse reflection:
Recursively call
getSuperclass
starting from the instance ofClass1
until you reachObject
.Use
Class.getSuperClass()
to traverse the hierarchy.