Java SE 6新特性: 编译器 API
http://tech.ddvip.com 2007年08月11日 社区交流
内容摘要:本文是其中的第四篇,介绍了 JDK 6 中为在运行时操纵编译器所增加的编译器 API(JSR 199)。您将了解到,利用此 API 开发人员可以在运行时调用 Java 编译器,还可以编译非文本形式的 Java 源代码,最后还能够采集编译器的诊断信息。
编译文件:int result = compiler.run(null, null, null, fileToCompile);
获得编译器对象之后,可以调用 Tool.run 方法对源文件进行编译。Run 方法的前三个参数,分别可以用来重定向标准输入、标准输出和标准错误输出,null 值表示使用默认值。清单 1 给出了一个完整的例子:
清单 1. 程序运行时编译文件
01 package compile;
02 import java.util.Date;
03 public class Target {
04 public void doSomething(){
05 Date date = new Date(10, 3, 3);
// 这个构造函数被标记为deprecated, 编译时会
// 向错误输出输出信息。
06 System.out.println("Doing...");
07 }
08 }
09 package compile;
10 import javax.tools.*;
11 import java.io.FileOutputStream;
12 public class Compiler {
13 public static void main(String[] args) throws Exception{
14 String fullQuanlifiedFileName = "compile" + java.io.File.separator +
"Target.java";
15 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
16 FileOutputStream err = new FileOutputStream("err.txt");
17 int compilationResult = compiler.run(null, null, err, fullQuanlifiedFileName);
18 if(compilationResult == 0){
19 System.out.println("Done");
20 } else {
21 System.out.println("Fail");
22 }
23 }
24 }
来源:ibm 作者:沈 羽 责编:豆豆技术应用
正在加载评论...