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. 开发者_JAVA技巧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?
You can use Java's reflection API in order to get information about types at runtime.
For example, you can use Class.getSuperclass() to walk the type tree upwards, and find the parents of a class.
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.
public void DisplaySuperClass(Class c)
{
System.out.println(c.getSuperclass().getName());
}
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)
精彩评论