小编典典
到目前为止,您需要扫描整个类路径(和子文件夹)以查找实现类的类java.sql.Driver。这样,您还将涵盖 没有
由手动Class#forName()或自动加载的驱动程序META-INF/services。
这是一个基本示例:
public static void main(String[] args) throws Exception {
List> drivers = findClassesImplementing(Driver.class);
System.out.println(drivers);
}
public static List> findClassesImplementing(Class cls) throws IOException {
List> classes = new ArrayList>();
for (URL root : Collections.list(Thread.currentThread().getContextClassLoader().getResources(""))) {
for (File file : findFiles(new File(root.getFile()), ".+\\.jar$")) {
JarFile jarFile = new JarFile(file);
for (JarEntry jarEntry : Collections.list(jarFile.entries())) {
String name = jarEntry.getName();
if (name.endsWith(".class")) try {
Class> found = Class.forName(name.replace("/", ".").replaceAll("\\.class$", ""));
if (cls.isAssignableFrom(found)) {
classes.add((Class) found);
}
} catch (Throwable ignore) {
// No real class file, or JAR not in classpath, or missing links.
}
}
}
}
return classes;
}
public static List findFiles(File directory, final String pattern) throws IOException {
File[] files = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory() || file.getName().matches(pattern);
}
});
List found = new ArrayList(files.length);
for (File file : files) {
if (file.isDirectory()) {
found.addAll(findFiles(file, pattern));
} else {
found.add(file);
}
}
return found;
}
Set> drivers = reflections.getSubTypesOf(Driver.class);
2020-11-16