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

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

问题描述

我正在制作一个可以编写.java文件的工具,然后(希望)将这些文件编译成.class文件。在一个过程中,用户选择写入多个.java文件的文件目录。现在我想让程序编译这些Java文件。

解决方案

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



这里有一个关于如何使用编译器API的例子

  JavaCompiler compiler = ToolProvider .getSystemJavaCompiler(); 
DiagnosticCollector< JavaFileObject> diagnostics = new DiagnosticCollector<>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics,null,null);
Iterable<?扩展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();


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 is your friend. Check the documentation here

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天全站免登陆