如何通过CompilationTask设置编译源 [英] How to set the source for compilation by a CompilationTask
问题描述
我不知道如何为 compilationTask
设置源文件。
I do not know how to set the source file for a compilationTask
.
我试过:
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();
但我得到以下错误:
线程main中的异常java.lang.IllegalArgumentException:不是有效的类名:src / Hello.java
Exception in thread "main" java.lang.IllegalArgumentException: Not a valid class name: src/Hello.java
$ b b
当然,如果我把null而不是类,我得到没有源文件,因为没有给出源文件。我之前尝试使用 JavaCompiler
的运行功能,但我不能在字符串参数中指定选项(或者我不知道如何)。
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).
这里是解决方案:
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();
推荐答案
尝试更改:
classes.add("src/Hello.java");
到:
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.
这篇关于如何通过CompilationTask设置编译源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!