使用另一个java程序编译一个java程序 [英] compiling a java program using another java program

查看:88
本文介绍了使用另一个java程序编译一个java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个java程序,从文件中读取另一个java程序,编译它并显示错误和警告。

I want to make a java program that reads another java program from a file, compiles it and shows error and warnings.

如何做到这一点?

推荐答案

查看 javax.tools.JavaCompiler


从程序中调用Java™编程语言编译器的接口。

Interface to invoke Java™ programming language compilers from programs.

编译器可能在编译期间生成诊断(例如,错误消息)。如果提供了诊断侦听器,则诊断将提供给侦听器。如果没有提供监听器,则诊断将以未指定的格式格式化,并写入缺省输出,即System.err,除非另有规定。即使提供了诊断侦听器,某些诊断可能不适合诊断,并且将写入默认输出。

The compiler might generate diagnostics during compilation (for example, error messages). If a diagnostic listener is provided, the diagnostics will be supplied to the listener. If no listener is provided, the diagnostics will be formatted in an unspecified format and written to the default output, which is System.err unless otherwise specified. Even if a diagnostic listener is supplied, some diagnostics might not fit in a Diagnostic and will be written to the default output.

以下是我最近使用的一些代码段:

Here's a little code-snippet I've used recently:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = 
       compiler.getStandardFileManager(null, null, null);

fileManager.setLocation(StandardLocation.CLASS_OUTPUT, compileDirList);


Iterable<? extends JavaFileObject> compilationUnits = 
       fileManager.getJavaFileObjectsFromFiles(files);

List<String> opts = new ArrayList<String>();
// set compiler's classpath to be same as the runtime's
opts.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path")));

// do the actual compilation
compiler.getTask(null, fileManager, null, opts, null, compilationUnits).call();

这篇关于使用另一个java程序编译一个java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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