本文介绍了如何确定类是否在Java中扩展另一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中如何确定类扩展的类?
In Java how do I go about determining what classes a class extends?
public class A{
}
public class B extends A{
}
public class C extends A{
}
public class D{
}
public class E extends B{
}
public class doSomething{
public void myFunc(Class cls){
//need to check that cls is a class which extends A
//i.e. B, C and E but not A or D
}
}
会 cls.getSuperClass()
做我需要的吗?
推荐答案
getSuperClass()
E
的方法会失败,因为它的直接超类不是 A
,但 B
。而是使用。
The getSuperClass()
approach would fail for E
since its immediate superclass is not A
, but B
. Rather use Class#isAssignableFrom()
.
public void myFunc(Class cls){
//need to check that cls is a class which extends A
//i.e. B, C and E but not A or D
if (cls != A.class && A.class.isAssignableFrom(cls)) {
// ...
}
}
这篇关于如何确定类是否在Java中扩展另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!