不幸的是,Java不提供一种简单的方法来列出“本地”JRE中的类。这给你留下几个选项:(a)对于任何给定的JAR文件,您可以列出该JAR文件中的条目,找到.class文件,然后确定每个.class文件表示哪个Java类;或者(b)您可以使用为您执行此操作的库。
选项(a):手动扫描JAR文件
在这个选项中,我们将使用jar文件中包含的所有Java类列表填充classNames /path/to/jar/file.jar。
List classNames = new ArrayList();
ZipInputStream zip = new ZipInputStream(new FileInputStream("/path/to/jar/file.jar"));
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
// This ZipEntry represents a class. Now, what class does it represent?
String className = entry.getName().replace('/', '.'); // including ".class"
classNames.add(className.substring(0, className.length() - ".class".length()));
}
}
选项(b):使用专门的反射库
番石榴
Guava已经有ClassPath,因为至少14.0,我已经使用和喜欢。 ClassPath的一个好处是它不会加载它找到的类,这在扫描大量类时非常重要。
ClassPath cp=ClassPath.from(Thread.currentThread().getContextClassLoader());
for(ClassPath.ClassInfo info : cp.getTopLevelClassesRecurusive("my.package.name")) {
// Do stuff with classes here...
}
反思
我没有亲自使用the Reflections library,但它似乎很喜欢。在网站上提供了一些很好的例子,像这样快速的方式加载所有的类在任何JAR文件提供的包,这也可能对您的应用程序有用。
Reflections reflections = new Reflections("my.project.prefix");
Set> subTypes = reflections.getSubTypesOf(SomeType.class);
Set> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class);