java 一个班级的所有超班级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5679254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
All super classes of a class
提问by Makky
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中做到这一点?
回答by Erik
Use Class.getSuperClass()
to traverse the hierarchy.
使用Class.getSuperClass()
遍历层次。
Class C = getClass();
while (C != null) {
System.out.println(C.getName());
C = C.getSuperclass();
}
回答by Jan Zyka
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.
但是首先阅读文档以了解它在接口等的情况下返回什么。在同一页面上有更多的方法可以使用。
回答by MarcoS
Recursively call getSuperclass
starting from the instance of Class1
until you reach Object
.
getSuperclass
从 的实例开始递归调用,Class1
直到到达Object
。
回答by Tovi7
Use reflection:
使用反射:
public static List<Class> getSuperClasses(Object o) {
List<Class> classList = new ArrayList<Class>();
Class class= o.getClass();
Class superclass = class.getSuperclass();
classList.add(superclass);
while (superclass != null) {
class = superclass;
superclass = class.getSuperclass();
classList.add(superclass);
}
return classList;
}
回答by Pops
The other answers are right about using Class.getSuperclass()
. But you have to do it repeatedly. Something like
关于使用Class.getSuperclass()
. 但你必须反复这样做。就像是
Class superClass = getSuperclass();
while(superClass != null) {
// do stuff here
superClass = superClass.getSuperclass();
}
回答by Dandre Allison
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