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.
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).
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.
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? It inherits all the superclass's attributes.
I think the simplest implementation is this
static Class<?> findClosestCommonSuper(Class<?> a, Class<?> b) {
while (!a.isAssignableFrom(b))
a = a.getSuperclass();
return a;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With