栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

查找已安装的JDBC驱动程序

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

查找已安装的JDBC驱动程序

到目前为止,您需要扫描整个类路径(和子文件夹)以查找实现类的类

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;}

相反,您也可以考虑使用Google Reflections
API
,该API可在一行中完成所有操作:

Set<Class<? extends Driver>> drivers = reflections.getSubTypesOf(Driver.class);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570492.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号