简体   繁体   中英

Dynamic loading of java class for activiti Service Task

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?

  • You cannot safely assume that the system classloader is an instance of URLClassLoader . Usually it is, but that might not be true for the next version of java.
  • No need to write your own classloader, 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).
  • No need to extract .class files, an ClassLoader knows how to load classes from a .jar file
  • You might want to set your custom classloader as current - something along Thread.currentThread().setContextClassLoader(l)
  • Eventually, you might load your classes using 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM