Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of "isAssignableFrom" for a Class object?

Tags:

java

class

Given a Class object, how do I check if one of its "ancestors" is a certain class? Is there an alternative to call getSuperClass several times?

like image 922
Zeemee Avatar asked Jul 11 '11 06:07

Zeemee


People also ask

What is isAssignableFrom?

isAssignableFrom() determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

Is assignable from VS Instanceof?

In other words, instanceof operator checks if the left object is same or subclass of right class, while isAssignableFrom checks if we can assign object of the parameter class (from) to the reference of the class on which the method is called.


2 Answers

Given a class c1, you want to know if one of its ancestors is c2?

Won't

c2.isAssignableFrom(c1)

do the trick?

like image 156
Ray Toal Avatar answered Sep 21 '22 02:09

Ray Toal


Can you not just flip the isAssignableFrom(...) logic, as follows?

public static void main(String[] args) {
    final Cat cat = new Cat();
    final Siamese siamese = new Siamese();

    // All print true
    System.out.println(cat.isSuperclass(Animal.class));
    System.out.println(siamese.isSuperclass(Animal.class));
    System.out.println(siamese.isSuperclass(Cat.class));

    // All print false
    System.out.println(cat.isSuperclass(Siamese.class));
    System.out.println(siamese.isSuperclass(Integer.class));
}

public static class Animal {

}

public static class Cat extends Animal {

    public boolean isSuperclass(final Class<?> cls) {
        return cls.isAssignableFrom(getClass());
    }
}

public static class Siamese extends Cat {

}
like image 38
hoipolloi Avatar answered Sep 22 '22 02:09

hoipolloi