给定一个Class对象,如何检查其中一个“祖先”是否属于某个类? 有几次调用getSuperClass的替代方法吗?
答案 0 :(得分:13)
鉴于课程c1
,您想知道其中一位祖先是c2
吗?
会不会
c2.isAssignableFrom(c1)
诀窍?
答案 1 :(得分:1)
你能不能只是翻转isAssignableFrom(...)逻辑,如下所示?
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 {
}