For stand-alone java application I can use the following codes to load jar lib dynamically during the runtime based on the library path. It seems not working if I deploy same codes in Java Web container and run as a servlet. I actually want to be able to load the different jar libs based on the jar lib path in servlet request.
It means that single servlet will have to be able to load different jar libs dynamically during runtime and run onward biz logic
user1 might request to load jar files under /tmp/lib/v1.0/.jar
user2 might request to load jar files under /tmp/lib/v1.1/.jar
(The jar files in v1.0 and v1.1 got the exactly same class names)
Thanks!!!
=== Main =============
LibraryLoader loader = new LibraryLoader();
loader.addClassPath(<jar lib root path>);
// below will run biz logic
=== LibraryLoader.java ==========
public class LibraryLoader {
URLClassLoader urlClassLoader;
public LibraryLoader() {
urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
}
public void addClassPath(String jarLibPath) throws Exception {
Class urlClass = URLClassLoader.class;
File jarPath = new File(jarLibPath);
FileFilter jarFilter = new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory())
return true;
String name = f.getName().toLowerCase();
return name.endsWith("jar");
}
};
File[] files = jarPath.listFiles(jarFilter);
for (File file : files) {
if (file.isFile()) {
URI uriPath = file.toURI();
URL urlPath = uriPath.toURL();
Method method = urlClass.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(urlClassLoader, new Object[] { urlPath });
System.out.println(file.getCanonicalPath());
} else {
addClassPath(file.getCanonicalPath());
}
}
}
}
that’s not what you want to do. even in your stand-alone program, this won’t really work (as you could be pushing multiple versions of the same jar into the main classloader). what you want to do is create a new classloader containing the new jars, then invoke some class in the new classloader.
e.g.:
of course, you probably want to cache these classloaders and re-use them on subsequent requests.
of course, i’m not sure why you don’t just deploy multiple versions of the servlet with the different versioned jars (since you indicate that the version is part of the servlet path).