清单 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 }
(编辑:aniston)
|