通过URLClassLoader实现动态加载jar文件

示例代码:

package t;

import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.util.Properties;

public class Test2 {

	public static void main(String[] args) throws Exception {

		String url = "jdbc:sqlserver://localhost:1433;DatabaseName=loushang";
		String user = "sa";
		String password = "loushang";
		String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		String driverJar = "file:/D:/Desktop/sqljdbc4.jar";
		
		URL urls[] = new URL[] { new URL(driverJar)};
		URLClassLoader loader = new URLClassLoader(urls);
		Class<?> clazz = loader.loadClass(driverClass);
		Driver driver = (Driver)clazz.newInstance();
		
		Properties p = new Properties();
		p.put("user", user);
		p.put("password", password);
		
		Connection con = driver.connect(url, p);
		DatabaseMetaData meta = con.getMetaData();
		System.out.println("getDatabaseProductName()="+meta.getDatabaseProductName());
		System.out.println("getDatabaseProductVersion()="+meta.getDatabaseProductVersion());
		System.out.println("getDefaultTransactionIsolation()="+meta.getDefaultTransactionIsolation());
		System.out.println("getDriverName()="+meta.getDriverName());
		con.close();
	}
}

 

 

输出结果:

getDatabaseProductName()=Microsoft SQL Server
getDatabaseProductVersion()=8.00.760
getDefaultTransactionIsolation()=2
getDriverName()=Microsoft SQL Server 2005 JDBC Driver

 

 

关于URLClassLoader:

java.net
类 URLClassLoader

java.lang.Object
  java.lang.ClassLoader
      java.security.SecureClassLoader
          java.net.URLClassLoader
直接已知子类:
MLet

public class URLClassLoader
extends SecureClassLoader
该类加载器用于从指向 JAR 文件和目录的 URL 的搜索路径加载类和资源。这里假定任何以 '/' 结束的 URL 都是指向目录的。如果不是以该字符结束,则认为该 URL 指向一个将根据需要打开的 JAR 文件。

http://huangqiqing123.iteye.com/blog/1461418

 

你可能感兴趣的:(ClassLoader)