Listing 2: Ancestry.java — Prints a class’s superclasses

import java.util.*;

class Ancestry
{
   public static void printAncestry(Class c)
   {
      // Walk up the inheritance path
      LinkedList stack = new LinkedList();
      stack.addFirst(c);
      while ((c = c.getSuperclass()) != null)
         stack.addFirst(c);

      // Print with java.lang.Object at top
      for (int i = 0; stack.size() > 0; ++i)
      {
         if (i > 0)
         {
            System.out.println("  ^");
         }
         Class cl = (Class)stack.removeFirst();
         System.out.println(cl.getName());
      }
   }

   public static void main(String[] args)
      throws ClassNotFoundException
   {
      printAncestry(Class.forName("Sub"));
   }
}

/* Output:
java.lang.Object
  ^
Super
  ^
Sub
*/
— End of Listing —