JSR 199引入了Java编译器API。如果使用JDK 6 的话,可以通过此API来动态编译Java
代码。
public class CompilerTest {
public static void main(String[] args) throws Exception
{
String source = "public class Main { public static void main(String[] args) {System.out.println(\"Hello World!\");} }";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager =compiler.getStandardFileManager(null, null, null);
StringSourceJavaObject sourceObject = new CompilerTest.StringSourceJavaObject("Main", 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("编译成功。");
}
}
static class StringSourceJavaObject extends SimpleJavaFileObject {
private String content = null;
public StringSourceJavaObject(String name, String content) throwsURISyntaxException
{
super(URI.create("string:///" + name.replace('.','/') +
Kind.SOURCE.extension), Kind.SOURCE);
this.content = content;
}
public CharSequence getCharContent(booleanignoreEncodingErrors) throws IOException
{
return content;
}
}
}
如果不能使用JKD1.6可以使用可以使用JDK 中的工具类com.sun.tools.javac.Main,不过该工具类只能编译存放在磁盘上的文件,类似于直接使用javac命令。
另外一个可用的工具是Eclipse JDT Core提供的编译器。这是Eclipse Java开发环境使用的增量式Java编译器,支持运行和调试有错误的代码。该编译器也可以单独使用。
使用这些动态编译的方式的时候,需要确保JDK中的tools.jar在应用的 CLASSPATH中。