获取Classpath中的所有类 [英] Get all of the Classes in the Classpath
问题描述
如何获取 CLASSPATH
在运行时?
在Eclipse IDE中,您可以通过按 Ctrl + < kbd> 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?
推荐答案
你可以通过传递一个空 String
到 ClassLoader#getResources()
。
You can get all classpath roots by passing an empty String
into ClassLoader#getResources()
.
Enumeration<URL> roots = classLoader.getResources("");
您可以构建 档案
docs.oracle.com/javase/6/docs/api/java/net/URLConnection.htmlrel =nofollow noreferrer> URL
如下:
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()) {
// ...
}
您可以使用标准< a href =http://docs.oracle.com/javase/6/docs/api/java/io/File.html =nofollow noreferrer> 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.
这篇关于获取Classpath中的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!