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

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

问题描述

我正在制作一个将编写 .java 文件的工具,然后(希望)将这些文件编译为 .class 文件.在一个过程中,用户选择一个文件目录,其中写入多个 .java 文件.现在我想让程序编译这些 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天全站免登陆