1.
/**
2.
*
3.
*/
4.
package de.tutorials;
5.
6.
import java.io.File;
7.
import java.lang.reflect.Method;
8.
import java.net.URL;
9.
import java.net.URLClassLoader;
10.
11.
/**
12.
* @author Thomas.Darimont
13.
*/
14.
public class DynamicClasspathExtensionExample {
15.
16.
/**
17.
* @param args
18.
*/
19.
public static void main(String[] args) {
20.
try {
21.
Class.forName("com.google.inject.Injector");
22.
System.out.println("Found");
23.
} catch (ClassNotFoundException e) {
24.
System.out.println(e.getMessage() + " not found...");
25.
}
26.
addJarsToClassPath(Thread.currentThread().getContextClassLoader(), new File[]{new File("D:/stuff/google/guice/1.0/guice-1.0.jar")});
27.
try {
28.
Class.forName("com.google.inject.Injector");
29.
System.out.println("Found");
30.
} catch (ClassNotFoundException e) {
31.
System.out.println(e.getMessage() + " not found...");
32.
}
33.
}
34.
35.
36.
private static void addJarsToClassPath(ClassLoader classLoader, File[] jars) {
37.
if (classLoader instanceof URLClassLoader) {
38.
try {
39.
Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
40.
addUrlMethod.setAccessible(true);
41.
if (null != addUrlMethod) {
42.
for (File jar : jars) {
43.
try {
44.
addUrlMethod.invoke(classLoader, jar.toURI().toURL());
45.
} catch (Exception e) {
46.
e.printStackTrace();
47.
}
48.
}
49.
}
50.
} catch (Exception e) {
51.
e.printStackTrace();
52.
}
53.
54.
}
55.
}
56.
}