首页

分享outerj的daisy-util实现自定义DriverLoader驱动类加载器对自定义classpath的driverClass进行加载实例化的源码

标签:DriverManager,驱动加载器,自定义类加载器,daisy-util,jdbcutil,URLClassLoader     发布时间:2018-01-16   

一、前言

通过outerj的daisy-util-1.4.1.jar的org.outerj.daisy.jdbcutil.DriverLoader自定义数据库驱动加载器,基于DriverManager.registerDriver注册自定义数据库驱动DriverShim,具体如下代码说明。

二、源码说明

package org.outerj.daisy.jdbcutil;@b@@b@import java.io.File;@b@import java.net.MalformedURLException;@b@import java.net.URL;@b@import java.net.URLClassLoader;@b@import java.sql.Connection;@b@import java.sql.Driver;@b@import java.sql.DriverManager;@b@import java.sql.DriverPropertyInfo;@b@import java.sql.SQLException;@b@import java.util.ArrayList;@b@import java.util.Properties;@b@import java.util.StringTokenizer;@b@@b@public class DriverLoader@b@{@b@  public static void loadDatabaseDriver(String classpath, String driverClass)@b@    throws Exception@b@  {@b@    ArrayList urls = new ArrayList();@b@    StringTokenizer tokenizer = new StringTokenizer(classpath, ",");@b@    while (tokenizer.hasMoreTokens()) {@b@      String filename = tokenizer.nextToken().trim();@b@      try@b@      {@b@        URL url = new File(filename).toURL();@b@        urls.add(url);@b@      }@b@      catch (MalformedURLException e)@b@      {@b@        throw new Exception("Invalid filename in driver path.", e);@b@      }@b@    }@b@    ClassLoader classLoader = new URLClassLoader((URL[])urls.toArray(new URL[0]), Thread.currentThread().getContextClassLoader());@b@    Driver driver = (Driver)Class.forName(driverClass, true, classLoader).newInstance();@b@    DriverManager.registerDriver(new DriverShim(driver));@b@  }@b@@b@  private static final class DriverShim@b@    implements Driver@b@  {@b@    private Driver driver;@b@@b@    DriverShim(Driver d)@b@    {@b@      this.driver = d;@b@    }@b@@b@    public final boolean acceptsURL(String u) throws SQLException@b@    {@b@      return this.driver.acceptsURL(u);@b@    }@b@@b@    public final Connection connect(String u, Properties p) throws SQLException@b@    {@b@      return this.driver.connect(u, p);@b@    }@b@@b@    public final int getMajorVersion()@b@    {@b@      return this.driver.getMajorVersion();@b@    }@b@@b@    public final int getMinorVersion()@b@    {@b@      return this.driver.getMinorVersion();@b@    }@b@@b@    public final DriverPropertyInfo[] getPropertyInfo(String u, Properties p) throws SQLException@b@    {@b@      return this.driver.getPropertyInfo(u, p);@b@    }@b@@b@    public final boolean jdbcCompliant()@b@    {@b@      return this.driver.jdbcCompliant();@b@    }@b@  }@b@}