Search code examples
javainheritancesuperclass

How do I find the nearest common superclass of two non-interface classes


To find the nearest common superclass, given two non-interface classes a and b, I do the following:

static Class<?> findClosestCommonSuper(final Class<?> a, final Class<?> b) {
    Iterator<Class<?>> pathA = pathFromObject(a).iterator();
    Iterator<Class<?>> pathB = pathFromObject(b).iterator();
    Class<?> res = Object.class;
    Class<?> c;
    while (pathA.hasNext() && pathB.hasNext()) {
        if ((c = pathA.next()) == pathB.next())
            res = c;
    }
    return res;
}

pathFromObject() returns a List<Class<?>> representing inheritance chain, starting from Object.class:

static List<Class<?>> pathFromObject(Class<?> cl) {
    List<Class<?>> res = new ArrayList<>();
    while (cl != null) {
        res.add(cl);
        cl = cl.getSuperclass();
    }
    Collections.reverse(res);
    return res;
}

My question is: does some out-of-the-box JDK solution exist for this? Maybe using classloader or some specific functionality. Or a better algorithm that doesn't require two iterations.


Solution

  • I think the simplest implementation is this

    static Class<?> findClosestCommonSuper(Class<?> a, Class<?> b) {
        while (!a.isAssignableFrom(b))
            a = a.getSuperclass();
        return a;
    }