29

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?

6 Answers 6

54

Use Class.getSuperClass() to traverse the hierarchy.

Class C = getClass();
while (C != null) {
  System.out.println(C.getName());
  C = C.getSuperclass();
}
1
  • Just to make sure, this would output: 1,2,3,4,5,6 if it would be C.getSimpleName() instead of C.getName()?
    – OuuGiii
    Jan 12, 2018 at 9:34
5

You can use getSuperclass() up to the Object.

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.

2
  • oh aye !! nice one ...thx ..call the loop until I get Object as a superclass !!:) ...
    – Makky
    Apr 15, 2011 at 15:52
  • Yes, or null ... see the doc :)
    – Jan Zyka
    Apr 15, 2011 at 15:54
4

As a variation, with a tight loop, you can use a for loop instead:

for (Class super_class = target_class.getSuperclass();
     super_class != null;
     super_class = super_class.getSuperclass())
  // use super class here
4

Recursively call getSuperclass starting from the instance of Class1 until you reach Object.

0
4

Use reflection:

public static List<Class> getSuperClasses(Object o) {
  List<Class> classList = new ArrayList<Class>();
  Class clazz = o.getClass();
  Class superclass = clazz.getSuperclass();
  classList.add(superclass);
  while (superclass != null) {   
    clazz = superclass;
    superclass = class.getSuperclass();
    classList.add(superclass);
  }
  return classList;
}
1
  • 1
    This will put null into the collection if you pass an instance of Object to the method. You should do all the class.getSuperclass() invocations in the while loop.
    – L. Blanc
    Aug 28, 2015 at 14:44
3

The other answers are right about using Class.getSuperclass(). But you have to do it repeatedly. Something like

Class superClass = getSuperclass();
while(superClass != null) {
    // do stuff here
    superClass = superClass.getSuperclass();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.