Search code examples
javareflectionparent

Is it possible to use Java Reflection or various techniques to check if a class has a parent class?


Possible Duplicate:
Is it possible to use Java Reflection to print out attributes of the parent class?

Hi, is it possible to use Java Reflection or various techniques to check if a class has a parent class?

This thought came as something for a need to create a utility class that takes in an object, print out its attributes, and if a parent class exists, to print out the attributes of the parent class.

Edit I meant to ask if there was a way to keep checking if a class had a mother class all the way up to the Object class.


Solution

  • Use this:

    Class<?> superClass = MyClass.class.getSuperClass();
    

    All superclasses:

    public static void printSuperClass(Class<?> clazz) {
      if (clazz == null) return;
    
      Class<?> superclass = clazz.getSuperClass();
      System.out.println(clazz.getName() + " extends " + superclass.getName());
      printSuperClass(superclass);
    }