简体   繁体   English

为activiti服务任务动态加载java类

[英]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.我需要动态加载一个 jar 并将其类提取到类路径,这样就不需要重新启动服务器。 This is for activi service task, where the java class will be available as a jar.这是用于 activi 服务任务,其中 java 类将作为 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.我尝试了类似下面的内容,但是在部署服务任务时,它给出了错误“无法实例化 packageName.className。”我猜这意味着找不到该类。

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?关于如何使用 OSGI 方法以外的自定义 classLoader 解决此问题的任何想法?

  • You cannot safely assume that the system classloader is an instance of URLClassLoader .您不能安全地假设系统类加载器是URLClassLoader的实例。 Usually it is, but that might not be true for the next version of java.通常是这样,但对于下一版本的 java 来说可能不是这样。
  • No need to write your own classloader, URLClassLoader just does fine.无需编写自己的类加载器, URLClassLoader就可以了。 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).当使用URLClassLoader(URL[] urls)构造函数实例化时,它将正确地委托给其父类加载器,因此您只需要自己的 .jar 文件的 URL。
  • No need to extract .class files, an ClassLoader knows how to load classes from a .jar file无需提取 .class 文件, ClassLoader知道如何从 .jar 文件加载类
  • You might want to set your custom classloader as current - something along Thread.currentThread().setContextClassLoader(l)您可能希望将自定义类加载器设置为当前类加载器 - 沿着Thread.currentThread().setContextClassLoader(l)
  • Eventually, you might load your classes using Class.forName("my.foo.class")最终,您可以使用Class.forName("my.foo.class")加载您的类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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