如何通过 CompilationTask 设置编译源
我不知道如何设置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
当然,如果我将 null 而不是类,我会得到“没有源文件”,因为没有给出源文件。在此之前我尝试使用 JavaCompiler 的 run 函数,但我无法在字符串参数中指定选项(或者我不知道如何指定)。
这是解决方案:
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();
I do not know how to set the source file for a 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: 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<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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下代码应该可以解决问题,尽管我在机器上运行代码时将路径设置为绝对路径:
The following code should solve the problem, though I made the paths absolute when I ran the code on my machine:
尝试将: 更改
为:
这有点冗长,但可以完成工作。当然可以将其提取到方法中。
Try changing:
to:
It's a bit verbose but does the job. Of course it could be extracted to a method.