I do not know how to set the source file for a compilationTask.
I tried this:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
List optionList = new ArrayList(Arrays.asList("-d","build/classes"));
List classes = new ArrayList();
classes.add("src/Hello.java");
CompilationTask task = compiler.getTask(null, null, null, optionList, classes, null);
task.call();
But I get the following error:
Exception in thread "main" java.lang.IllegalArgumentException: Not a valid class name: src/Hello.java
of course, if I put null instead of classes I get "no source files" as no source file was given. I tried using the run function of the JavaCompiler before this but I could not specify the options in the string arguments (Or I do not know how).
Here is the solution:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
List optionList = new ArrayList(Arrays.asList("-d","build/classes"));
Iterable extends JavaFileObject> classes = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(new File("src/Hello.java")));
CompilationTask task = compiler.getTask(null, null, null, optionList,null, classes);
task.call();
解决方案
Try changing:
classes.add("src/Hello.java");
to:
classes.add(
new SimpleJavaFileObject(new URI("src/Hello.java"), JavaFileObject.Kind.SOURCE)
);
It's a bit verbose but does the job. Of course it could be extracted to a method.