My dynamic compilation in Java 6 is working perfectly. However, I would like to change the output path. I have tried tons of things (I'll spare you) to no avail. Anyway, here's the working code
String[] filesToCompile = { "testFiles/Something.java" };
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(filesToCompile);
CompilationTask task = compiler.getTask(null, fileManager, null,null, null, compilationUnits);
System.out.println("Good? " + task.call());
But the output goes to the source directory, which is not what I want.
I suspect that the answer may lie in the compiler.getTask
but the API is not very explicit as to what some of the parameters might mean. Or perhaps something with the fileManager. I've tried
fileManager.setLocation(StandardLocation.locationFor("testFiles2"), null);
but again, guessing is probably not a good idea.
Thanks!
Edit: I've tried using options, too, like this (sorry if there's a more compact way):
final List<String> optionsList = new ArrayList<String>();
optionsList.add("-d what");
Iterable<String> options = new Iterable<String>() {
public Iterator<String> iterator() {
return optionsList.iterator();
}
};
and then passing the options to getTask, but error message is "Invalid Flag."
Code in the first post would work, but the following error get's thrown:
java.lang.IllegalArgumentException: invalid flag: -d folder
This is because by passing "-d folder"
makes the parser think it's parsing one option. The options must be separated like "-d", "folder"
.
Working example follows:
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager sjfm = javaCompiler.getStandardFileManager(null, null, null);
String[] options = new String[] { "-d", "output" };
File[] javaFiles = new File[] { new File("src/gima/apps/flip/TestClass.java") };
CompilationTask compilationTask = javaCompiler.getTask(null, null, null,
Arrays.asList(options),
null,
sjfm.getJavaFileObjects(javaFiles)
);
compilationTask.call();