Finding Superclasses


Class cls = obj.getClass(); Class superclass = cls.getSuperclass();



The ancestors of a given class are referred to as that class's superclasses. Using reflection, you can determine all of the ancestors of a given class. After you've obtained a Class object, you can use the getSuperclass() method to get the class's superclass if one exists. If a superclass exists, a Class object will be returned. If there is not a superclass, this method will return null. Remember that Java supports only single inheritance, so for any given class, there can be only one superclass. Actually to be clear, there can be only one direct superclass. Technically, all ancestor classes are considered to be superclasses of a given class. To retrieve all ancestor superclasses, you would recursively call the getSuperclass() method on each Class object that is returned.

The method shown here will print all the superclasses associated with the object passed in:

static void printSuperclasses(Object obj) {    Class cls = obj.getClass();    Class superclass = cls.getSuperclass();    while (superclass != null) {       String className = superclass.getName();       System.out.println(className);       cls = superclass;       superclass = cls.getSuperclass();    } }


Often an Integrated Development Environment (IDE) such as Eclipse will include a class browser as a feature. The class browser allows the developer to visually navigate through a hierarchy of classes. This technique is one of the ways in which class browsers are constructed. In order to build a visual class browser, your application must be able to determine which classes are the superclasses of any given class.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net