Java Reflection Super Class findSuperTypes(Class cls, Class endBefore)

Here you can find the source of findSuperTypes(Class cls, Class endBefore)

Description

Method that will find all sub-classes and implemented interfaces of a given class or interface.

License

Open Source License

Parameter

Parameter Description
endBefore Super-type to NOT include in results, if any; when encountered, will be ignored (and no super types are checked).

Declaration

public static List<Class<?>> findSuperTypes(Class<?> cls, Class<?> endBefore) 

Method Source Code

//package com.java2s;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class Main {
    /**//from  w ww.  j av a 2  s . com
     * Method that will find all sub-classes and implemented interfaces
     * of a given class or interface. Classes are listed in order of
     * precedence, starting with the immediate super-class, followed by
     * interfaces class directly declares to implemented, and then recursively
     * followed by parent of super-class and so forth.
     * Note that <code>Object.class</code> is not included in the list
     * regardless of whether <code>endBefore</code> argument is defined or not.
     *
     * @param endBefore Super-type to NOT include in results, if any; when
     *    encountered, will be ignored (and no super types are checked).
     */
    public static List<Class<?>> findSuperTypes(Class<?> cls, Class<?> endBefore) {
        return findSuperTypes(cls, endBefore, new ArrayList<Class<?>>());
    }

    public static List<Class<?>> findSuperTypes(Class<?> cls, Class<?> endBefore, List<Class<?>> result) {
        _addSuperTypes(cls, endBefore, result, false);
        return result;
    }

    private static void _addSuperTypes(Class<?> cls, Class<?> endBefore, Collection<Class<?>> result,
            boolean addClassItself) {
        if (cls == endBefore || cls == null || cls == Object.class) {
            return;
        }
        if (addClassItself) {
            if (result.contains(cls)) { // already added, no need to check supers
                return;
            }
            result.add(cls);
        }
        for (Class<?> intCls : cls.getInterfaces()) {
            _addSuperTypes(intCls, endBefore, result, true);
        }
        _addSuperTypes(cls.getSuperclass(), endBefore, result, true);
    }
}

Related

  1. getAllSuperClass(Class clazz, boolean includesObjectClass)
  2. getAllSuperclasses(Class cls)
  3. getAllSuperclasses(Class cls)
  4. getAllSuperclasses(Class clazz)