title: How to get the JavaCompiler to use a provided classLoader to find a class?
body: <p>I am using <a href="http://www.ibm.com/developerworks/library/j-jcomp/" rel="nofollow">this code</a> from an old IBM blog post about how to compile and use Java classes at runtime. The code mostly works great (and is quite well written, by the way), but unfortunately for me, it won't work in one of my use cases where the class being compiled refers to another class that can only be provided by the classLoader provided to the <code>CharSequenceCompiler</code> (from the blog post), not by the application classLoader.</p>
  
  <p>To be more specific, The ClassLoader I pass into <code>CharSequenceCompiler</code> is a OSGi classLoader.</p>
  
  <p>The bundle that owns this classLoader can find and return a class, say <code>Foo</code>.</p>
  
  <pre><code>class Foo { public static String FOO = "F"; }
  </code></pre>
  
  <p>I know this works if you do <code>classLoader.findClass("Foo");</code> because when I call this from the debugger it works.</p>
  
  <p>Now, from the class I compile at runtime, say <code>Dynamic</code>, I need to use <code>Foo</code>... so I pass the <code>Foo</code> bundle's ClassLoader to <code>CharSequenceCompiler</code>, then ask it to compile <code>Dynamic</code>:</p>
  
  <pre><code>class Dynamic { public static String D = Foo.FOO; }
  </code></pre>
  
  <p>This causes the following error:</p>
  
  <pre><code>error: cannot find symbol
  Foo.FOO;
  ^
  symbol:   variable Foo
  </code></pre>
  
  <p>If <code>Foo</code> is in the same project as <code>CharSequenceCompiler</code>, then it works... so it's clearly a problem loading the class from the right class loader.</p>
  
  <p>I have debugged this code for days (or evenings, tbh) and can't find out why the classLoader I provide to the compiler never even gets asked about this class...</p>
  
  <p>The <code>FileManager</code> is asked to <code>list()</code> the resources in each package, but even when I use the debugger to manually add the <code>FileObject</code> to the returned list, it still won't work.</p>
  
  <p>As the debugger cannot penetrate the native classes used by javac internally, I cannot progress anymore on this... does anyone have inside knowledge of the compiler that could explain what's going on?</p>