Can you find all classes in a package using reflection?(您可以使用反射找到包中的所有类吗?)
问题描述
是否可以找到给定包中的所有类或接口?(快速查看例如 Package
,好像没有.)
Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. Package
, it would seem like no.)
推荐答案
由于类加载器的动态特性,这是不可能的.类加载器不需要告诉虚拟机它可以提供哪些类,它们只是传递给类的请求,并且必须返回一个类或抛出一个异常.
Due to the dynamic nature of class loaders, this is not possible. Class loaders are not required to tell the VM which classes it can provide, instead they are just handed requests for classes, and have to return a class or throw an exception.
但是,如果您编写自己的类加载器,或检查类路径及其 jar,则可以找到这些信息.这将通过文件系统操作,而不是反射.甚至可能有一些库可以帮助您做到这一点.
However, if you write your own class loaders, or examine the classpaths and it's jars, it's possible to find this information. This will be via filesystem operations though, and not reflection. There might even be libraries that can help you do this.
如果有生成的类或远程交付的类,您将无法发现这些类.
If there are classes that get generated, or delivered remotely, you will not be able to discover those classes.
通常的方法是在某个文件中注册您需要访问的类,或者在不同的类中引用它们.或者只是在命名时使用约定.
The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming.
附录:反射库将允许您在当前类路径中查找类.它可用于获取包中的所有类:
Addendum: The Reflections Library will allow you to look up classes in the current classpath. It can be used to get all classes in a package:
Reflections reflections = new Reflections("my.project.prefix");
Set<Class<? extends Object>> allClasses =
reflections.getSubTypesOf(Object.class);
这篇关于您可以使用反射找到包中的所有类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:您可以使用反射找到包中的所有类吗?


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01