/* * 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. */ /** * ShowAllInterfaces.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 8-2: * Modify the program you wrote in Exercise 8-1 so that it prints out all inter- * faces implemented by a specified class or by any of its superclasses. Check * for the case of classes that implement interfaces that extend other interfaces. * For example, if a class implements java.awt.LayoutManager2, the LayoutManager2 * interface and LayoutManager, its superinterface, should be listed. * * @author Matthew Feldt * @version 1.0, 04/16/2001 19:10 */ package com.feldt.examples.reflect; import java.util.*; public class ShowAllInterfaces { static final String USAGE = "Usage: java ShowAllInterfaces "; private static ArrayList interfaces = new ArrayList(); ShowAllInterfaces(Class c) { loadAllInterfaces(c); } private void loadAllInterfaces(Class c) { Class superclass = c.getSuperclass(); Class[] classInterfaces = c.getInterfaces(); // class contains interfaces if interfaces.length != 0 if (classInterfaces.length != 0) { // iterate through all interfaces to see if any implement other // interfaces not yet recorded for (int i = 0; i < classInterfaces.length; i++) { // add interface name if not yet recorded if (! interfaces.contains(classInterfaces[i].getName())) { interfaces.add(classInterfaces[i].getName()); } } } if (superclass != null) { // root class if superclass == null loadAllInterfaces(superclass); // recurse } } public String[] getAllInterfaces() { return (String[])interfaces.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]); ShowAllInterfaces sai = new ShowAllInterfaces(c); String[] interfaces = sai.getAllInterfaces(); System.out.println(); System.out.println("Interfaces:"); for (int i = 0; i < interfaces.length; i++) { System.out.println(interfaces[i]); } } catch (ClassNotFoundException e) { System.err.println(e.getMessage()); System.exit(-1); } } }