使用URLClassLoader在运行时动态加载驱动类

/**
     * 根据驱动类名和jar路径,动态创建驱动对象
     * @param className 驱动类名
     * @param localPathList 驱动jar或目录位置
     * @return Driver 驱动对象
     */
    public Driver getDriverFromJar(String className, List localPathList) {
        try {
            List urlList = localPathList.stream().map(path ->{
                //从path转为URL
                File driverJar =new File(path);
                try {
                    return driverJar.toURI().toURL();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                return null;
            }).collect(toList());
            URLClassLoader classLoader = new URLClassLoader(urlList.toArray(new URL[urlList.size()])
                    , Thread.currentThread().getContextClassLoader());
            Class jdbcClass = classLoader.loadClass(className);
            Object object = jdbcClass.getDeclaredConstructor().newInstance();
            if (object instanceof Driver) {
                return (Driver) object;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

你可能感兴趣的:(开发语言,java)