A-A+
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.
1
2 import java.net.URL;
3 import java.io.IOException;
4 import java.net.URLClassLoader;
5 import java.net.MalformedURLException;
6
7 public class JarFileLoader extends URLClassLoader
8 {
9 public JarFileLoader (URL[] urls)
10 {
11 super (urls);
12 }
13
14 public void addFile (String path) throws MalformedURLException
15 {
16 String urlPath = "jar:file://" + path + "!/";
17 addURL (new URL (urlPath));
18 }
19
20 public static void main (String args [])
21 {
22 try
23 {
24 System.out.println ("First attempt...");
25 Class.forName ("org.gjt.mm.mysql.Driver");
26 }
27 catch (Exception ex)
28 {
29 System.out.println ("Failed.");
30 }
31
32 try
33 {
34 URL urls [] = {};
35
36 JarFileLoader cl = new JarFileLoader (urls);
37 cl.addFile ("/opt/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar");
38 System.out.println ("Second attempt...");
39 cl.loadClass ("org.gjt.mm.mysql.Driver");
40 System.out.println ("Success!");
41 }
42 catch (Exception ex)
43 {
44 System.out.println ("Failed.");
45 ex.printStackTrace ();
46 }
47 }
48 }