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?
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.
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.
Given a class c1
, you want to know if one of its ancestors is c2
?
Won't
c2.isAssignableFrom(c1)
do the trick?
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 {
}
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