Java SE 6新特性: 编译器 API
http://tech.ddvip.com 2007年08月11日 社区交流
内容摘要:本文是其中的第四篇,介绍了 JDK 6 中为在运行时操纵编译器所增加的编译器 API(JSR 199)。您将了解到,利用此 API 开发人员可以在运行时调用 Java 编译器,还可以编译非文本形式的 Java 源代码,最后还能够采集编译器的诊断信息。
清单 4. 编译非文本形式的源文件
01 package math;
02 import javax.tools.*;
03 import java.io.FileOutputStream;
04 import java.util.Arrays;
05 public class AdvancedCompiler {
06 public static void main(String[] args) throws Exception{
07 // Steps used to compile Calculator
08 // Steps used to compile StringObject
09 // construct CalculatorTest in memory
10 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
11 StandardJavaFileManager fileManager =
compiler.getStandardFileManager(null, null, null);
12 JavaFileObject file = constructTestor();
13 Iterable<? extends JavaFileObject> files = Arrays.asList(file);
14 JavaCompiler.CompilationTask task = compiler.getTask (
null, fileManager, null, null, null, files);
15 Boolean result = task.call();
16 if( result == true ) {
17 System.out.println("Succeeded");
18 }
19 }
20 private static SimpleJavaFileObject constructTestor() {
21 StringBuilder contents = new StringBuilder(
"package math;" +
"class CalculatorTest {
" +
" public void testMultiply() {
" +
" Calculator c = new Calculator();
" +
" System.out.println(c.multiply(2, 4));
" +
" }
" +
" public static void main(String[] args) {
" +
" CalculatorTest ct = new CalculatorTest();
" +
" ct.testMultiply();
" +
" }
" +
"}
");
22 StringObject so = null;
23 try {
24 so = new StringObject("math.CalculatorTest", contents.toString());
25 } catch(Exception exception) {
26 exception.printStackTrace();
27 }
28 return so;
29 }
30 }
来源:ibm 作者:沈 羽 责编:豆豆技术应用
正在加载评论...