出于好奇,我通过隔离类加载器实现了您的第二种方法。它似乎正在工作:
public class DriverWrapper implements Driver {
private Driver target;
private String fakePrefix;
private String realPrefix;
protected DriverWrapper(Driver target, String fakePrefix, String realPrefix) {
this.target = target;
this.fakePrefix = fakePrefix;
this.realPrefix = realPrefix;
}
public static void loadDriver(URL[] classPath, String className, String fakePrefix, String actualPrefix)
throws Exception{
URLClassLoader cl = new URLClassLoader(classPath, DriverWrapper.class.getClassLoader());
Class<?> c = cl.loadClass(className);
// It's rather rude, but we haven't access to the existing instance anyway
Driver d = (Driver) c.newInstance();
Driver w = new DriverWrapper(d, fakePrefix, actualPrefix);
// We don't care about already registerd instance,
// because driver loaded in isolated classloader
// is not visible to the rest of application, see DriverManager javadoc
DriverManager.registerDriver(w);
}
private String resolveURL(String url) {
if (url.startsWith(fakePrefix)) {
return realPrefix + url.substring(fakePrefix.length());
} else {
return null;
}
}
public boolean acceptsURL(String url) throws SQLException {
url = resolveURL(url);
if (url == null) {
return false;
} else {
return target.acceptsURL(url);
}
}
public Connection connect(String url, Properties info) throws SQLException {
url = resolveURL(url);
if (url == null) {
return null;
} else {
return target.connect(url, info);
}
}
public int getMajorVersion() {
return target.getMajorVersion();
}
public int getMinorVersion() {
return target.getMinorVersion();
}
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
return target.getPropertyInfo(url, info);
}
public boolean jdbcCompliant() {
return target.jdbcCompliant();
}
}
按如下方式使用(驱动程序 jar 不应位于主类路径中):
DriverWrapper.loadDriver(new URL[] { new File("ojdbc5.jar").toURL() },
"oracle.jdbc.OracleDriver", "jdbc:oracle5", "jdbc:oracle");
DriverWrapper.loadDriver(new URL[] { new File("ojdbc14.jar").toURL() },
"oracle.jdbc.OracleDriver", "jdbc:oracle14", "jdbc:oracle");
... DriverManager.getConnection("jdbc:oracle14:...", ...);
... DriverManager.getConnection("jdbc:oracle5:...", ...);