您可以使用反射找到包中的所有类吗?
是否可以找到给定包中的所有类或接口?(快速查看例如 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);
相关文章