通過JavaCompiler進行編譯都是在當前目錄下生成
Iterable options = Arrays
JavaCompiler
diagnostics
在上面的例子中options處的參數為null
有時我們編譯一個Java源程序文件
Iterable options = Arrays
上面的代碼指定的被編譯Java文件所依賴的源文件所在的目錄
三
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/27244.html