编程语言

img cleverdeer

显示一个对象的继承等级,Class类的应用

发表于2004/9/29 11:07:00  458人阅读

这个小程序显示了一个给定对象的继承等级,采用了递归算法,可以显示对象继承的所有类和实现的所有接口。
//Hierarchy.java
import java.util.*;
import javax.swing.*;

public class Hierarchy {
  public static void showSuperClasses(Class c) {
    Class superClass = c.getSuperclass();
    if (superClass != null) {
      prt(superClass.getName());
      showSuperClasses(superClass);
    }
  }

  public static void showSuperClasses(Object o) {
    showSuperClasses(o.getClass());
  }

  public static void showInterfaces(Class c) {
    Class[] interfaces = c.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
      prt(interfaces[i].getName());
      showInterfaces(interfaces[i]);
    }
  }

  public static void showInterfaces(Object o) {
    showInterfaces(o.getClass());
  }

  public static void showHierarchy(Class c) {
    Class superClass = c.getSuperclass();
    Class[] interfaces = c.getInterfaces();

    if (superClass != null) {
      prt("extends: ");
      prt(superClass.getName());
      showHierarchy(superClass);
    }

    for (int i = 0; i < interfaces.length; i++) {
      prt("implements:");
      prt(interfaces[i].getName());
      showHierarchy(interfaces[i]);
    }
  }

  public static void showHierarchy(Object o) {
    showHierarchy(o.getClass());
  }

  public static void prt(String s) {
    System.out.println(s);
  }

  public static void main(String[] args) {
    //showSuperClasses(new ArrayList());
    //showInterfaces(new ArrayList());
    showHierarchy(new Z1());
  }
}

interface A1 {}

interface A2
    extends A1 {}

interface B1 {}

interface B2
    extends B1 {}

interface C1 {}

interface C2
    extends C1 {}

class X1 implements A2{}
class Y1 implements B2{}
class Z1 extends X1 implements C2{}

阅读全文
0 0

相关文章推荐

img
取 消
img