import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
public class CompilerTest {
public static void main(String[] args) throws Exception {
String CLASSNAME = "TestClass";
String source = "public class " + CLASSNAME +" { public static void main(String[] args) {System.out.println(/"Hello World!/");} }";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
JavaSourceFromString sourceObject = new JavaSourceFromString(CLASSNAME,source);
Iterable extends JavaFileObject> fileObjects = Arrays.asList(sourceObject);
CompilationTask task = compiler.getTask(null, fileManager, null, null,null, fileObjects);
boolean result = task.call();
if (result) {
System.out.println("编译成功。");
Runtime r = Runtime.getRuntime();
Process p = r.exec("java " + CLASSNAME);
BufferedReader br = new BufferedReader(new InputStreamReader(p
.getInputStream()));
StringBuffer sb = new StringBuffer();
String inline;
while (null != (inline = br.readLine())) {
sb.append(inline).append("/n");
}
System.out.println(sb.toString());
}
}
}
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;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}