import java.lang.reflect.*; import java.io.*; import javax.tools.*; import javax.tools.JavaCompiler.CompilationTask; import java.util.*; import java.net.*;
public class test_compilerapi { private static void compilerJava() throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); // 定义一个StringWriter类,用于写Java程序 StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); // 开始写Java程序 out.println("public class HelloWorld {"); out.println(" public static void main(String args[]) {"); out.println(" System.out.println(\"Hello, World\");"); out.println(" }"); out.println("}"); out.close(); //为这段代码取个名子:HelloWorld,以便以后使用reflection调用 JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString()); Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file); JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits); boolean success = task.call(); System.out.println("Success: " + success); // 如果成功,通过reflection执行这段Java程序 if (success) { System.out.println("-----输出-----"); Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null }); System.out.println("-----输出 -----"); } } public static void main(String args[]) throws Exception { compilerJava(); } } // 用于传递源程序的JavaSourceFromString类 class JavaSourceFromString extends SimpleJavaFileObject { final String code; JavaSourceFromString(String name, String code) { super(URI.create("string:///" + name.replace('.', '/')+ Kind.SOURCE.extension), Kind.SOURCE); this.code = code; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } } |