Search code examples
javainheritancemultiple-inheritance

Is it possible to check if one class is extending another in java without making instances?


I have two Class<? extends SomeClass> variables, one obtained from looping the keys of a HashMap, we'll call it A, and one passed as a parameter, which we'll call B. I'd like to see if B extends A.

So, as I currently understand things, I'd make an instance of B (using createInstance) and check instanceof. But this is not only pretty slow, but cumbersome as classes need an empty constructor. See here and here, where they discuss isAssignableFrom and getSuperClass, but isAssignableFrom (from what I read there) doesn't work on the same class (SomeClass.isAssignableFrom(SomeClass) ?), and getSuperClass doesn't walk up the tree.

Is there a way I can check if B extends A without creating an instance of B?

For example:

class SomeClass {}
class ExtendingClassA extends SomeClass {}
class ExtendingClassAB extends ExtendingClassA {}
class ExtendingClassB extends SomeClass {}
boolean ClassExtendsClass(Class<? extends SomeClass> A,Class<? extends SomeClass> B) {
    return A.class instanceof B.class;
}
ClassExtendsClass(SomeClass.class, ExtendingClassA.class); //true
ClassExtendsClass(SomeClass.class, ExtendingClassAB.class); //true
ClassExtendsClass(SomeClass.class, ExtendingClassB.class); //true
ClassExtendsClass(ExtendingClassA.class, ExtendingClassB.class); //false

Solution

  • Yup. Generally, check the API (javadoc) of the type you think would be the right place for it. In this case, that'd be Class itself, and, luckily, it's there:

    Class<?> a = Integer.class;
    Class<?> b = Number.class;
    System.out.println(b.isAssignableFrom(a));
    System.out.println(b.isAssignableFrom(b));
    > true
    > true
    

    but isAssignableFrom (from what I read there) doesn't work on the same class

    You should test that stuff before making assumptions. It works fine.