/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * ShowSuperClasses.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 8-1: * Write a program that takes the name of a Java class as a command-line argument * and uses the Class class to print out all the superclasses of that class. * For example, if invoked with the argument "java.applet.Applet", the program * prints the following: java.lang.Object java.awt.Component java.awt.Container * java.awt.Panel. * * @author Matthew Feldt * @version 1.0, 04/14/2001 19:07 */ package com.feldt.examples.reflect; import java.util.*; public class ShowSuperClasses { static final String USAGE = "Usage: java ShowSuperClasses "; private static ArrayList superclasses = new ArrayList(); ShowSuperClasses(Class c) { loadSuperClasses(c); } /** populate the superclasses array */ private void loadSuperClasses(Class c) { Class superclass = c.getSuperclass(); // get superclass if any if (superclass != null) { // root class if superclass == null superclasses.add(superclass.getName()); // add class name loadSuperClasses(superclass); // recurse } } /** return a String listing the super classes of the specified class */ public String[] getSuperClasses() { return (String[])superclasses.toArray(new String[0]); } public static void main(String[] args) throws ClassNotFoundException { try { if (args.length != 1) throw new IllegalArgumentException( "Incorrect number of command line arguments."); Class c = Class.forName(args[0]); ShowSuperClasses ssc = new ShowSuperClasses(c); String[] superclasses = ssc.getSuperClasses(); System.out.println(); System.out.println("Super Classes:"); for (int i = 0; i < superclasses.length; i++) { System.out.println(superclasses[i]); } } catch (Exception e) { System.err.println(e.getMessage()); System.exit(-1); } } }