List<String> getClassPath() ; 获取 classpath 下所有的 类信息
时间: 2023-05-22 07:03:00 浏览: 124
基于java类路径classpath和包的实例讲解
可以使用以下代码获取 classpath 下的所有类信息:
```
List<String> classNames = new ArrayList<>();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String classPath = System.getProperty("java.class.path");
String[] classPathEntries = classPath.split(System.getProperty("path.separator"));
for (String classPathEntry : classPathEntries) {
File classFile = new File(classPathEntry);
if (!classFile.exists()) {
continue;
}
if (classFile.isDirectory()) {
String[] classFiles = classFile.list((dir, name) -> name.endsWith(".class"));
if (classFiles == null) {
continue;
}
for (String classFileName : classFiles) {
classNames.add(classFileName.substring(0, classFileName.length() - 6));
}
} else {
try (JarFile jarFile = new JarFile(classFile)) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String jarEntryName = jarEntry.getName();
if (!jarEntryName.endsWith(".class")) {
continue;
}
String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replace("/", ".");
classNames.add(className);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文