获取类路径中的所有类 [英] Get all of the Classes in the Classpath
问题描述
如何获取 CLASSPATH
在运行时?
在 Eclipse IDE 中,您可以通过按 Ctrl+Shift+T 来执行此操作.
Java 中有什么方法可以完成它吗?
How can I get list of all available classes in CLASSPATH
at runtime?
In Eclipse IDE, you can do this by pressing Ctrl+Shift+T.
Is there any method in Java to get it done?
推荐答案
您可以通过向 ClassLoader#getResources()
.
You can get all classpath roots by passing an empty String
into ClassLoader#getResources()
.
Enumeration<URL> roots = classLoader.getResources("");
You can construct a File
based on URL
as follows:
File root = new File(url.getPath());
您可以使用File#listFiles()
获取给定目录中所有文件的列表:
You can use File#listFiles()
to get a list of all files in the given directory:
for (File file : root.listFiles()) {
// ...
}
您可以使用标准的java.io.File
方法来检查它是否是一个目录和/或获取文件名.
You can use the standard java.io.File
methods to check if it's a directory and/or to grab the filename.
if (file.isDirectory()) {
// Loop through its listFiles() recursively.
} else {
String name = file.getName();
// Check if it's a .class file or a .jar file and handle accordingly.
}
根据唯一的功能要求,我猜 Reflections 库 更准确你想要什么.
Depending on the sole functional requirement, I guess that the Reflections library is much more exactly what you want.
这篇关于获取类路径中的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!