****更新 1 (2012)****
好的,我终于开始清理下面的代码 sn-p 了。我将它嵌入到它自己的 github 项目中,甚至添加了测试。
https://github.com/ddopson/java-class-enumerator
****更新 2 (2016)****
有关更强大且功能丰富的类路径扫描器,请参阅https://github.com/classgraph/classgraph。我建议先阅读我的代码 sn-p 以获得更高层次的理解,然后将 lukehutch 的工具用于生产目的。
****原帖 (2010)****
严格来说,不可能列出包中的类。这是因为包实际上只不过是一个命名空间(例如 com.epicapplications.foo.bar),并且类路径中的任何 jar 文件都可能将类添加到包中。更糟糕的是,类加载器会按需加载类,而类路径的一部分可能位于网络连接的另一端。
可以解决更严格的问题。例如,JAR 文件中的所有类,或 JAR 文件在特定包中定义的所有类。无论如何,这是更常见的情况。
不幸的是,没有任何框架代码可以使这项任务变得简单。您必须以类似于 ClassLoader 查找类定义的方式扫描文件系统。
网络上有很多关于普通目录中类文件的示例。如今,我们大多数人都使用 JAR 文件。
要使用 JAR 文件,试试这个...
private static ArrayList<Class<?>> getClassesForPackage(Package pkg) {
String pkgname = pkg.getName();
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
// Get a File object for the package
File directory = null;
String fullPath;
String relPath = pkgname.replace('.', '/');
System.out.println("ClassDiscovery: Package: " + pkgname + " becomes Path:" + relPath);
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
System.out.println("ClassDiscovery: Resource = " + resource);
if (resource == null) {
throw new RuntimeException("No resource for " + relPath);
}
fullPath = resource.getFile();
System.out.println("ClassDiscovery: FullPath = " + resource);
try {
directory = new File(resource.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", e);
} catch (IllegalArgumentException e) {
directory = null;
}
System.out.println("ClassDiscovery: Directory = " + directory);
if (directory != null && directory.exists()) {
// Get the list of the files contained in the package
String[] files = directory.list();
for (int i = 0; i < files.length; i++) {
// we are only interested in .class files
if (files[i].endsWith(".class")) {
// removes the .class extension
String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);
System.out.println("ClassDiscovery: className = " + className);
try {
classes.add(Class.forName(className));
}
catch (ClassNotFoundException e) {
throw new RuntimeException("ClassNotFoundException loading " + className);
}
}
}
}
else {
try {
String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
JarFile jarFile = new JarFile(jarPath);
Enumeration<JarEntry> entries = jarFile.entries();
while(entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if(entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {
System.out.println("ClassDiscovery: JarEntry: " + entryName);
String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
System.out.println("ClassDiscovery: className = " + className);
try {
classes.add(Class.forName(className));
}
catch (ClassNotFoundException e) {
throw new RuntimeException("ClassNotFoundException loading " + className);
}
}
}
} catch (IOException e) {
throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e);
}
}
return classes;
}