查找已安装的JDBC驱动程序

Ste*_*aux 7 java jdbc

我正在用Java编写数据库验证工具并具有首选项屏幕,因此用户可以定义其数据库连接.该工具应该能够至少应对DB2,Oracle,Postgresql和Mysql.

我真正想要的是能够向用户提供他们已安装的jdbc驱动程序列表作为此过程的一部分.

任何人都可以提供代码片段来发现已安装的JDBC驱动程序吗?

Bal*_*usC 9

到目前为止,您需要扫描整个类路径(和子文件夹)以实现类java.sql.Driver.这样,您还将覆盖由人工手动加载Class#forName()或自动加载的驱动程序META-INF/services.

这是一个基本的例子:

public static void main(String[] args) throws Exception {
    List<Class<Driver>> drivers = findClassesImplementing(Driver.class);
    System.out.println(drivers);
}        

public static <T extends Object> List<Class<T>> findClassesImplementing(Class<T> cls) throws IOException {
    List<Class<T>> classes = new ArrayList<Class<T>>();

    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<T>) found);
                    }
                } catch (Throwable ignore) {
                    // No real class file, or JAR not in classpath, or missing links.
                }
            }
        }
    }

    return classes;
}

public static List<File> 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<File> found = new ArrayList<File>(files.length);

    for (File file : files) {
        if (file.isDirectory()) {
            found.addAll(findFiles(file, pattern));
        } else {
            found.add(file);
        }
    }

    return found;
}
Run Code Online (Sandbox Code Playgroud)

相反,您也可以考虑使用Google Reflections API,它可以在一行中执行此操作:

Set<Class<? extends Driver>> drivers = reflections.getSubTypesOf(Driver.class);
Run Code Online (Sandbox Code Playgroud)