你能用反射找到包中的所有类吗? [英] Can you find all classes in a package using reflection?

查看:112
本文介绍了你能用反射找到包中的所有类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以找到给定包中的所有类或接口? (快速查看例如 Package ,它似乎没有。)

解决方案

由于课堂的动态性装载机,这是不可能的。类加载器不需要告诉VM它可以提供哪些类,而是只需要提交类的请求,并且必须返回一个类或抛出异常。



但是,如果您编写自己的类加载器,或检查类路径及其罐子,则可以找到此信息。这将通过文件系统操作,而不是反射。甚至可能有库可以帮助你这样做。



如果有类生成或远程交付,你将无法发现这些类。 / p>

普通方法是在某处注册您需要在文件中访问的类,或者在不同的类中引用它们。或者只是在命名时使用约定。



附录: Reflections库将允许您在当前类路径中查找类。它可用于获取包中的所有类:

 反射反射=新反射(my.project.prefix) ; 

设置< Class<? extends Object>> allClasses =
reflections.getSubTypesOf(Object.class);


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.

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);

这篇关于你能用反射找到包中的所有类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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