集册 Java实例教程 查找多个类中最接近的公共超类

查找多个类中最接近的公共超类

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

591
查找多个类中最接近的公共超类


//package com.nowjava;

import java.util.Collections;/*from nowjava*/

import java.util.HashSet;


public class Main {

    /**

     * Find the closest common superclass of multiple classes

     * 

     * @param cs

     * @return

     */

    @SuppressWarnings("rawtypes")

    public static Class FindCommonSuperclass(Class[] cs) {

        if (cs.length == 0) {

            return Object.class;

        } else if (cs.length == 1) {

            return cs[0];

        }
/*n o w j a v a . c o m - 时  代  Java 提供*/

        // if any items fail getSuperclass in the passed in array,

        // simply return object.

        boolean isSame = true;

        boolean hasNullSuperclass = false;

        for (Class c : cs) {

            if (c == null)

                throw new NullPointerException();

            if (c != cs[0])

                isSame = false;

            if (c.getSuperclass() == null)

                hasNullSuperclass = true;

        }

        // no need to do further calculations.. all the same

        if (isSame)

            return cs[0];

        // at least one item in the list failed getSuperclass... return object

        if (hasNullSuperclass)

            return Object.class;


        Class c1 = cs[0];

        Class c2 = null;

        HashSet<Class> s1 = new HashSet<>();

        HashSet<Class> s2 = new HashSet<>();


        for (int i = 1; i < cs.length; i++) {

            s1.clear();

            s2.clear();

            c2 = cs[i];


            do {

                s1.add(c1);

                s2.add(c2);

                if (c1 != Object.class) {

                    c1 = c1.getSuperclass();

                }

                if (c2 != Object.class) {

             
展开阅读全文