I need to dynamically load a jar and extract its classes to the classpath, so that there is no need of restarting the server. This is for activi service task, where the java class will be available as a jar. I tried out something like below, but at the point where the service task is deployed it gives error "Cannot instantiate packageName.className. " Which i guess means that the class cannot be found.
URLClassLoader loader = (URLClassLoader)ClassLoader.getSystemClassLoader();
log.info("LOADER" +loader.getURLs());
MyClassLoader l = new MyClassLoader(loader.getURLs());
l.addURL(new URL("jar","","file:"+artifactLocation+"!/"));
JarFile jarFile = new JarFile(artifactLocation);
Enumeration e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
// -6 because of .class
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
Class c = l.loadClass(className);
Any idea on how to solve this with a custom classLoader other than the OSGI method?
URLClassLoader
. Usually it is, but that might not be true for the next version of java.URLClassLoader
just does fine. And when instantiated with the URLClassLoader(URL[] urls)
constructor, it will properly delegate to its parent classloader, so you just need the URL of your own .jar file(s).ClassLoader
knows how to load classes from a .jar fileThread.currentThread().setContextClassLoader(l)
Class.forName("my.foo.class")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.