在 Java 中获取类层次结构?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4871697/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:25:44  来源:igfitidea点击:

Getting the Class hierarchy in Java?

java

提问by Sonam

I have a specific problem, which Eclipse solves perfectly, but I need a programmatic solution. What I want to do is get the "Type hierarchy" of any class that I provide. Eclipse does show a solution on pressing Ctrl+T, but how does it achieve this? Are there any APIs available so that I can use them?

我有一个特定的问题,Eclipse 完美地解决了这个问题,但我需要一个程序化的解决方案。我想要做的是获取我提供的任何类的“类型层次结构”。Eclipse 确实显示了按Ctrl+的解决方案T,但它是如何实现的?是否有任何可用的 API 以便我可以使用它们?

回答by Avi

You can use Java's reflection APIin order to get information about types at runtime.

您可以使用 Java 的反射 API在运行时获取有关类型的信息。

For example, you can use Class.getSuperclass()to walk the type tree upwards, and find the parents of a class.

例如,您可以使用Class.getSuperclass()向上遍历类型树,并找到一个类的父类。

回答by helloworld922

Java has a Reflection API which you can use to determine the base class of whatever class you have, as well as any interfaces that particular class implements. Determining what classes inherit from that class is going to be a bit more difficult, though. The reflection API also lets you do a lot of other stuff, too like determine what the members of that class are, and even call methods of that class and more.

Java 有一个反射 API,您可以使用它来确定您拥有的任何类的基类,以及特定类实现的任何接口。但是,确定从该类继承哪些类将更加困难。反射 API 还可以让您做很多其他的事情,比如确定该类的成员是什么,甚至调用该类的方法等等。

public void DisplaySuperClass(Class c)
{
    System.out.println(c.getSuperclass().getName());
}

回答by Jochen Bedersdorfer

There is however no easy way to find all subclasses of a class. For this you would have to load all the classes in your classpath (which can be many many thousand) and build this tree yourself, possibly through a custom ClassLoader(and only if you are resistant to pain you want to go there)

然而,没有简单的方法可以找到一个类的所有子类。为此,您必须加载类路径中的所有类(可能有数千个)并自己构建这棵树,可能是通过自定义ClassLoader(并且仅当您对痛苦有抵抗力时才想去那里)