从Java内部编译外部.java文件 [英] Compiling external .java files from within Java

查看:180
本文介绍了从Java内部编译外部.java文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个工具,它将写入.java文件,然后(希望)将这些文件编译为.class文件。在一个进程中,用户选择一个文件目录,其中写入多个.java文件。

I am making a tool that will write .java files, then (hopefully) compile those files to .class files. All in one process, the user selects a file directory where multiple .java files are written. Now I want the program to compile these Java files.

推荐答案

JavaCompiler 是你的朋友。检查此处的文档

JavaCompiler is your friend. Check the documentation here

这里是如何使用编译器API的示例

And here an example on how you could use the compiler API

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList("YouFileToCompile.java"));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null,
        null, compilationUnits);
boolean success = task.call();
fileManager.close();

这篇关于从Java内部编译外部.java文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆