你如何在 Java 中找到给定类的所有子类? [英] How do you find all subclasses of a given class in Java?

查看:48
本文介绍了你如何在 Java 中找到给定类的所有子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何尝试在 Java 中查找给定类(或给定接口的所有实现者)的所有子类?到目前为止,我有一种方法可以做到这一点,但我发现它效率很低(至少可以这么说).方法是:

How does one go about and try to find all subclasses of a given class (or all implementors of a given interface) in Java? As of now, I have a method to do this, but I find it quite inefficient (to say the least). The method is:

  1. 获取存在于类路径中的所有类名的列表
  2. 加载每个类并测试它是否是所需类或接口的子类或实现者

在 Eclipse 中,有一个很好的特性,称为类型层次结构,可以非常有效地显示这一点.如何以编程方式进行操作?

In Eclipse, there is a nice feature called the Type Hierarchy that manages to show this quite efficiently. How does one go about and do it programmatically?

推荐答案

除了您所描述的之外,没有其他方法可以做到.想一想——如果不扫描类路径上的每个类,怎么能知道哪些类扩展了 ClassX?

There is no other way to do it other than what you described. Think about it - how can anyone know what classes extend ClassX without scanning each class on the classpath?

Eclipse 只能在看似有效"的时间内告诉您有关超类和子类的信息,因为在您按下在类型层次结构中显示"按钮时,它已经加载了所有类型数据(因为它不断地编译你的类,知道类路径上的一切,等等).

Eclipse can only tell you about the super and subclasses in what seems to be an "efficient" amount of time because it already has all of the type data loaded at the point where you press the "Display in Type Hierarchy" button (since it is constantly compiling your classes, knows about everything on the classpath, etc).

这篇关于你如何在 Java 中找到给定类的所有子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆