I am using this code 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 CharSequenceCompiler
(from the blog post), not by the application classLoader.
To be more specific, The ClassLoader I pass into CharSequenceCompiler
is a OSGi classLoader.
The bundle that owns this classLoader can find and return a class, say Foo
.
class Foo { public static String FOO = "F"; }
I know this works if you do classLoader.findClass("Foo");
because when I call this from the debugger it works.
Now, from the class I compile at runtime, say Dynamic
, I need to use Foo
... so I pass the Foo
bundle's ClassLoader to CharSequenceCompiler
, then ask it to compile Dynamic
:
class Dynamic { public static String D = Foo.FOO; }
This causes the following error:
error: cannot find symbol
Foo.FOO;
^
symbol: variable Foo
If Foo
is in the same project as CharSequenceCompiler
, then it works... so it's clearly a problem loading the class from the right class loader.
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...
The FileManager
is asked to list()
the resources in each package, but even when I use the debugger to manually add the FileObject
to the returned list, it still won't work.
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?