My usage case is compiling generated source files from a java program using the ToolProvider and JavaCompiler classes provided in JDK 6. The source files contain references to classes in the context classloader (it runs in a J2EE container), but not in the system classloader. My understanding is that by default the ToolProvider will create the JavaCompiler instance with the system classloader.
Is there a way to specify a classloader for JavaCompiler to use?
I tried this approach, modified from something on IBM DeveloperWorks:
FileManagerImpl fm =
new FileManagerImpl(compiler.getStandardFileManager(null, null, null););
with FileManagerImpl defined as:
static final class FileManagerImpl
extends ForwardingJavaFileManager<JavaFileManager> {
public FileManagerImpl(JavaFileManager fileManager) {
super(fileManager);
}
@Override
public ClassLoader getClassLoader(JavaFileManager.Location location) {
new Exception().printStackTrace();
return Thread.currentThread().getContextClassLoader();
}
}
The stacktrace indicates it's only called once during annotation processing. I verified the class referenced in the source file to be compiled is not on the system classpath but is available from the context classloader.