三
JavaCompiler不僅可以編譯硬盤上的Java文件
import java
import java
import javax
import javax
import java
import java
public class test_compilerapi
{
private static void compilerJava() throws Exception
{
JavaCompiler compiler = ToolProvider
DiagnosticCollector diagnostics = new DiagnosticCollector();
// 定義一個StringWriter類
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
// 開始寫Java程序
out
out
out
out
out
out
//為這段代碼取個名子
JavaFileObject file = new JavaSourceFromString(
Iterable compilationUnits = Arrays
JavaCompiler
diagnostics
boolean success = task
System
// 如果成功
if (success)
{
System
Class
{ String[]
{ null });
System
}
}
public static void main(String args[]) throws Exception
{
compilerJava();
}
}
// 用於傳遞源程序的JavaSourceFromString類
class JavaSourceFromString extends SimpleJavaFileObject
{
final String code;
JavaSourceFromString(String name
{
super(URI
this
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors)
{
return code;
}
}
[
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27240.html