java java列出父类的所有子类

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

java list all the child classes of a parent

javainheritancereflection

提问by MBZ

Possible Duplicate:
At runtime, find all classes in a Java application that extend a base class

可能的重复:
在运行时,查找 Java 应用程序中扩展基类的所有类

I need to get list of all the classes (child) which extends a particular class (parent) and then create an instance of them all.

我需要获取扩展特定类(父类)的所有类(子类)的列表,然后创建所有类的实例。

how should I do this in Java?

我应该如何在 Java 中执行此操作?

回答by Peter Lawrey

I would use http://code.google.com/p/reflections/

我会使用http://code.google.com/p/reflections/

Using Reflections you can query your metadata such as:

  • get all subtypes of some type
  • get all types/methods/fields annotated with some annotation, w/o annotation parameters matching
  • get all resources matching matching a regular expression

使用反射,您可以查询元数据,例如:

  • 获取某种类型的所有子类型
  • 获取所有类型/方法/字段的注释,不带注释参数匹配
  • 获取匹配正则表达式的所有资源

This can be used in an indexed or cached mode. As @Jagger suggests, a brute force search of every class is relatively slow. You can also limit the search by package e.g. com.mycom.*

这可以在索引或缓存模式下使用。正如@Jagger 所暗示的那样,对每个类的蛮力搜索相对较慢。您还可以按包限制搜索,例如com.mycom.*