title: Load a class to Java classpath dynamically using Eclipse and OSGi
body: <p>Combining the information from many posts on this site and many others, I got the following code to dynamically add (at run time) a directory containing classes to the classpath and load a class within that directory.</p>
  
  <p><strong>I'm using OSGi bundles and running from eclipse an "Eclipse Application" (a kind of Run Configuration).</strong></p>
  
  <p>This is the code I'm using:</p>
  
  <p>CASE 1: (both cases are different things I've tried to do the same thing.)</p>
  
  <pre><code>File file = new File("/Users/alek/fastFIX/myJPass/"); 
  URL url = file.toURI().toURL(); 
  URL[] urls = new URL[]{url}; 
  ClassLoader cl = new URLClassLoader(urls); 
  Class  cls = cl.loadClass("GuiLauncher");    //the file GuiLauncher.class is in the /Users/alek/fastFIX/myJPass/ directory
  Class[] argTypes = new Class[] { String[].class };
  Method main = cls.getDeclaredMethod("main", argTypes); //trying to run the main class
  main.invoke(null, (Object) args);
  </code></pre>
  
  <p>I don't get any error, and nothing happens.
  I've also tryied the following, as I actually need the loaded class to interact with other (already loaded) classes.</p>
  
  <p>CASE 2:</p>
  
  <pre><code>ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
  URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {  new File("/Users/alek/fastFIX/myJPass/").toURL() }, currentThreadClassLoader);
  Thread.currentThread().setContextClassLoader(urlClassLoader);
  </code></pre>
  
  <p>then i load like this:</p>
  
  <pre><code> Class&lt;?&gt; c = Class.forName("GuiLauncher");
  </code></pre>
  
  <p>or like this:</p>
  
  <pre><code>Class&lt;?&gt; c = Thread.currentThread().getContextClassLoader().loadClass("GuiLauncher");
  </code></pre>
  
  <p>and try to invoke the main function like this:</p>
  
  <pre><code>Class[] argTypes = new Class[] { String[].class };
  Method main = cls.getDeclaredMethod("main", argTypes); //trying to run the main class
  main.invoke(null, (Object) args);
  </code></pre>
  
  <p>here also nothing happens.</p>
  
  <p>Any clue of what could be happening? I've read all related posts here and many places else with no luck.</p>