Returns the inheritance hierarchy of the specified class. - Java Reflection

Java examples for Reflection:Super Class

Description

Returns the inheritance hierarchy of the specified class.

Demo Code


//package com.java2s;
import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        System.out.println(java.util.Arrays
                .toString(getInheritanceHierarchy(clazz)));
    }//ww  w.ja va2  s.  c om

    /**
     * Returns the inheritance hierarchy of the specified class.
     * The returned array includes all superclasses of the specified class
     * starting with the most general superclass, which is
     * <code>java.lang.Object</code>. The returned array also
     * includes the class itself as the last element. Implemented
     * interfaces are not included.
     * @param clazz the Class
     * @return all superclasses, most general superclass first
     */
    public static Class[] getInheritanceHierarchy(Class clazz) {
        List classes = new ArrayList();
        Class currentClass = clazz;
        while (null != currentClass) {
            classes.add(currentClass);
            currentClass = currentClass.getSuperclass();
        }
        Collections.reverse(classes);
        return (Class[]) classes.toArray(new Class[classes.size()]);
    }
}

Related Tutorials