title: Dealing with dynamic libraries loading
body: <p>I have a jar, which contains all needed external libs. All i want: load libraries in runtime so i can use them as i could if they were in classpath.</p>
  
  <p>Some visualization:</p>
  
  <p><code>-main.jar</code><br>
  <code>-lib.jar</code><br>
  <code>--apache.jar</code><br>
  <code>--someother.jar</code><br>
  <code>---aclass.class</code><br>
  etc.</p>
  
  <p>Some not really helpful code:</p>
  
  <pre><code>    // loading libraries
      ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
      ArrayList&lt;URL&gt; librariesJarsURL = new ArrayList&lt;&gt;();
      JarFile libJar = new JarFile(libBundle);
      Enumeration libJarEnum = libJar.entries();
      while (libJarEnum.hasMoreElements()) {
          JarEntry libJarEntry = (JarEntry) libJarEnum.nextElement();
          if (!libJarEntry.isDirectory() &amp;&amp; libJarEntry.getName().endsWith(".jar")) {
              librariesJarsURL.add(new URL("jar:file://" + (libBundle.getAbsolutePath().replace("\\", "/")) + "!/" + libJarEntry.getName()));
          }
      }
      if (librariesJarsURL.size() &gt; 0) {
          for (URL libraryJarURL : librariesJarsURL) {
              System.out.println(libraryJarURL);
          }
          ClassLoader urlCL = URLClassLoader.newInstance(librariesJarsURL.toArray(new URL[0]), contextCL);
          Thread.currentThread().setContextClassLoader(urlCL);
      }
      System.out.println(StringUtils.difference("zero", "zero141"));
  </code></pre>
  
  <p>The last is from Commons Apache String utils that also should be included but aint giving me NoClassDefFoundError and ClassNotFoundException.</p>
  
  <p>Also, i tried to use "reflection hack" but it aint working as well.</p>
  
  <p>Thats the problem, guys... Any ideas?</p>
  
  <p>EDIT: <code>libBundle is kinda File object...</code></p>
  
  <p>UPD:</p>
  
  <pre><code>/*
   * Reflection hack :/
   */
  public static void addURL(URL url) throws Exception
  {
      URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
      Class uclclass = URLClassLoader.class;
  
      // Use reflection
      Method method = uclclass.getDeclaredMethod("addURL", new Class[]{URL.class});
      method.setAccessible(true);
      method.invoke(classLoader, new Object[]{url});
  }
  </code></pre>
  
  <p>Used <code>libBundle.toURI().toURL()</code> - same errors,<br>
  <code>addURL(new URL("jar:file://" + (libBundle.getAbsolutePath().replace("\\", "/")) + "!/"));</code> - thats same,<br>
  tried to do same with all jars in lib.jar - same.<br>
  Tried <code>URLClassLoader libraryLoader = new URLClassLoader(librariesJarsURL.toArray(new URL[0]), GlobalInit.class.getClassLoader());</code> - same.</p>