How to set source for compilation using CompilationTask

I do not know how to set the source file for compilationTask .

I tried this:

 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); List<String> optionList = new ArrayList<String>(Arrays.asList("-d","build/classes")); List<String> classes = new ArrayList<String>(); 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: Invalid class name: src / Hello.java

of course, if I put null instead of classes, I get "no source files" because the source file is not specified. I tried using the JavaCompiler startup function before that, but I could not specify the parameters in the string arguments (or I do not know how to do this).

Here is the solution:

 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); List<String> optionList = new ArrayList<String>(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(); 
+1
source share
2 answers

The following code should solve the problem, although I did the absolute paths when I ran the code on my machine:

 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fm = compiler.getStandardFileManager(diagnostics, null, null); ArrayList<String> optionList = new ArrayList<String>(Arrays.asList("-d","build/classes")); ArrayList<File> files = new ArrayList<File>(); files.add(new File("src/Hello.java")); CompilationTask task = compiler.getTask(null, null, null, optionList, null, fm.getJavaFileObjectsFromFiles(files)); task.call(); 
0
source

Try changing:

 classes.add("src/Hello.java"); 

in

 classes.add( new SimpleJavaFileObject(new URI("src/Hello.java"), JavaFileObject.Kind.SOURCE) ); 

This is a bit detailed, but does the job. Of course, it can be extracted for the method.

0
source

All Articles