[英]All super classes of a class
I have a class that extends to another class and that class extends to another class.我有一个扩展到另一个类的类,并且该类扩展到另一个类。
class 1 extends class 2
class 2 extends class 3
class 3 extends class 4
class 4 extends class 5
class 5 extends class 6
Now I want to find all super classes of class 1.现在我想找到第 1 类的所有超类。
Anyone know how I could do that in java?有谁知道我怎么能在java中做到这一点?
Use Class.getSuperClass()
to traverse the hierarchy.使用
Class.getSuperClass()
遍历层次结构。
Class C = getClass();
while (C != null) {
System.out.println(C.getName());
C = C.getSuperclass();
}
You can use getSuperclass()
up to the Object
.您可以使用
getSuperclass()
直到Object
。
But read the doc first to understand what it returns in the case of interfaces etc. There are more methods to play with on the same page.但是首先阅读文档以了解它在接口等的情况下返回什么。在同一页面上有更多的方法可以使用。
As a variation, with a tight loop, you can use a for
loop instead:作为变体,对于紧密循环,您可以改用
for
循环:
for (Class super_class = target_class.getSuperclass();
super_class != null;
super_class = super_class.getSuperclass())
// use super class here
从Class1
的实例开始递归调用getSuperclass
,直到到达Object
。
Use reflection:使用反射:
public static List<Class> getSuperClasses(Object o) {
List<Class> classList = new ArrayList<Class>();
Class clazz = o.getClass();
Class superclass = clazz.getSuperclass();
classList.add(superclass);
while (superclass != null) {
clazz = superclass;
superclass = class.getSuperclass();
classList.add(superclass);
}
return classList;
}
The other answers are right about using Class.getSuperclass()
.关于使用
Class.getSuperclass()
的其他答案是正确的。 But you have to do it repeatedly.但你必须反复这样做。 Something like
就像是
Class superClass = getSuperclass();
while(superClass != null) {
// do stuff here
superClass = superClass.getSuperclass();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.