集册 Java实例教程 返回指定类实现的所有接口,包括超类实现的所有接口。

返回指定类实现的所有接口,包括超类实现的所有接口。

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

451
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
返回指定类实现的所有接口,包括超类实现的所有接口。
/*
N  o w  J a v a . c o m
*/


//package com.nowjava;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.HashSet;

import java.util.List;

import java.util.Set;


public class Main {

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

        Class clazz = String.class;

        System.out.println(java.util.Arrays

                .toString(getImplementedInterfaces(clazz)));

    }

    /* from 
    n o w j a   v  a . c o m - 时  代  Java*/

    /**

     * Returns all interfaces implemented by the specified class

     * including all interfaces implemented by super classes.

     * If the specified class is itself an interfaces or the

     * specified class does not implement any interfaces, this

     * method returns an empty array.

     * @param clazz the Class

     * @return all interfaces implemented by the specified class

     */

    public static Class[] getImplementedInterfaces(Class clazz) {

        if (clazz.isInterface())

            return new Class[0];

        Class[] classes = getInheritanceHierarchy(clazz);

        Set interfaceSet = new HashSet();

        for (int ii = 0; ii < classes.length; ii++) {

            interfaceSet.addAll(Arrays.asList(classes[ii].getInterfaces()));

        }

        return (Class[]) interfaceSet

                .toArray(new Class[interfaceSet.size()]);

    }


    /**

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