集册 Java实例教程 找到所有子项的方法

找到所有子项的方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

414
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
查找给定类或接口的所有子类和已实现接口的方法。


//package com.nowjava;//N  o w  J a v a . c o m 提 供


import java.util.ArrayList;

import java.util.Collection;

import java.util.List;


public class Main {

    public static void main(String[] argv) throws Exception {

        Class cls = String.class;

        Class endBefore = String.class;

        System.out.println(findSuperTypes(cls, endBefore));

    }


    /**

     * 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<?>>());

    }
//from 时   代    Java - nowjava.com

    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 (addClassI
展开阅读全文