获取类路径中的所有类
2022-08-31 20:56:26
如何在运行时获取 CLASSPATH
中所有可用类的列表?
在 Eclipse IDE 中,可以通过按 ++ 来执行此操作。
Java中有什么方法可以完成它吗?CtrlShiftT
如何在运行时获取 CLASSPATH
中所有可用类的列表?
在 Eclipse IDE 中,可以通过按 ++ 来执行此操作。
Java中有什么方法可以完成它吗?CtrlShiftT
您可以通过将空值传递到 ClassLoader#getResources()
中来获取所有类路径根目录。String
Enumeration<URL> roots = classLoader.getResources("");
File root = new File(url.getPath());
您可以使用 File#listFiles()
获取给定目录中所有文件的列表:
for (File file : root.listFiles()) {
// ...
}
您可以使用标准的java.io.File
方法来检查它是否是目录和/或获取文件名。
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.
}
根据唯一的功能要求,我猜反射库更符合您的要求。
这是我写的。我敢肯定,如果你对类路径做任何奇怪的事情,它不会得到一切,但它似乎对我很好。请注意,它实际上并不加载类,它只是返回它们的名称。这样它就不会将所有类加载到内存中,并且由于我们公司代码库中的某些类如果在错误的时间加载,则会导致初始化错误...
public interface Visitor<T> {
/**
* @return {@code true} if the algorithm should visit more results,
* {@code false} if it should terminate now.
*/
public boolean visit(T t);
}
public class ClassFinder {
public static void findClasses(Visitor<String> visitor) {
String classpath = System.getProperty("java.class.path");
String[] paths = classpath.split(System.getProperty("path.separator"));
String javaHome = System.getProperty("java.home");
File file = new File(javaHome + File.separator + "lib");
if (file.exists()) {
findClasses(file, file, true, visitor);
}
for (String path : paths) {
file = new File(path);
if (file.exists()) {
findClasses(file, file, false, visitor);
}
}
}
private static boolean findClasses(File root, File file, boolean includeJars, Visitor<String> visitor) {
if (file.isDirectory()) {
for (File child : file.listFiles()) {
if (!findClasses(root, child, includeJars, visitor)) {
return false;
}
}
} else {
if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
JarFile jar = null;
try {
jar = new JarFile(file);
} catch (Exception ex) {
}
if (jar != null) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
int extIndex = name.lastIndexOf(".class");
if (extIndex > 0) {
if (!visitor.visit(name.substring(0, extIndex).replace("/", "."))) {
return false;
}
}
}
}
}
else if (file.getName().toLowerCase().endsWith(".class")) {
if (!visitor.visit(createClassName(root, file))) {
return false;
}
}
}
return true;
}
private static String createClassName(File root, File file) {
StringBuffer sb = new StringBuffer();
String fileName = file.getName();
sb.append(fileName.substring(0, fileName.lastIndexOf(".class")));
file = file.getParentFile();
while (file != null && !file.equals(root)) {
sb.insert(0, '.').insert(0, file.getName());
file = file.getParentFile();
}
return sb.toString();
}
}
要使用它:
ClassFinder.findClasses(new Visitor<String>() {
@Override
public boolean visit(String clazz) {
System.out.println(clazz)
return true; // return false if you don't want to see any more classes
}
});