DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Add A Jar File To Java Load Path At Run Time
Sometimes it is necessary to amend the class load path at run time. For example, dynamically adding jar files containing user-configurable JDBC data sources. The way this is done is truly monstrous -- the URL Path format was only revealed when a colleague looked into the Java library sources.
import java.net.URL;
import java.io.IOException;
import java.net.URLClassLoader;
import java.net.MalformedURLException;
public class JarFileLoader extends URLClassLoader
{
public JarFileLoader (URL[] urls)
{
super (urls);
}
public void addFile (String path) throws MalformedURLException
{
String urlPath = "jar:file://" + path + "!/";
addURL (new URL (urlPath));
}
public static void main (String args [])
{
try
{
System.out.println ("First attempt...");
Class.forName ("org.gjt.mm.mysql.Driver");
}
catch (Exception ex)
{
System.out.println ("Failed.");
}
try
{
URL urls [] = {};
JarFileLoader cl = new JarFileLoader (urls);
cl.addFile ("/opt/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar");
System.out.println ("Second attempt...");
cl.loadClass ("org.gjt.mm.mysql.Driver");
System.out.println ("Success!");
}
catch (Exception ex)
{
System.out.println ("Failed.");
ex.printStackTrace ();
}
}
}






Comments
Snippets Manager replied on Tue, 2010/09/21 - 3:23pm
"); } catch (Exception ex) { System.out.println ("In Exception Block -- Failed."); ex.printStackTrace (System.out); } } } >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Here are the logging messages %%%% true %%%% true %%%% true Success! --> com.ibm.db2.jcc.DB2Driver@24442444 BEFORE CONNECTION In Exception Block -- Failed. java.sql.SQLException: No suitable driver at java.sql.DriverManager.getConnection(DriverManager.java:582) at java.sql.DriverManager.getConnection(DriverManager.java:186) at com.tdbfg.tdsecurities.kasper.admin.aboutkasper.JarFileLoader1.main(JarFileLoader1.java:61)
Bedla Czech replied on Fri, 2010/03/26 - 3:53pm
public void addFile(String path) throws MalformedURLException { String urlPath = "jar:file:/" + path + "!/"; addURL(new URL(urlPath)); }Thank callingcl.addFile("c:/java/testability-explorer/testability-explorer-1.3.2.jar");