您可以使用反射找到包中的所有类吗?

Can you find all classes in a package using reflection?(您可以使用反射找到包中的所有类吗?)
本文介绍了您可以使用反射找到包中的所有类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

是否可以找到给定包中的所有类或接口?(快速查看例如 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);

这篇关于您可以使用反射找到包中的所有类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)