Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 935
Alex Salauyou Avatar asked Apr 08 '16 21:04

Alex Salauyou


People also ask

What is subclassing in Java?

In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class).

What is the super class in Java?

In Java, as in other object-oriented programming languages, classes can be derived from other classes. The derived class (the class that is derived from another class) is called a subclass. The class from which its derived is called the superclass.

Can private class be inherited in Java?

No, the private member are not inherited because the scope of a private member is only limited to the class in which it is defined. Only the public and protected member are inherited.

What does a subclass inherit from its superclass?

What does a subclass inherit from its superclass? It inherits all the superclass's attributes.


Video Answer


1 Answers

I think the simplest implementation is this

static Class<?> findClosestCommonSuper(Class<?> a, Class<?> b) {
    while (!a.isAssignableFrom(b))
        a = a.getSuperclass();
    return a;
}
like image 189
Paul Boddington Avatar answered Oct 01 '22 05:10

Paul Boddington