如果使用JDK1.6的话,可以通过此API来动态编译java代码。如果不使用可以使用JDK中的工具类
com.sun.tools.javac.Main,该类只能编译存放在磁盘上的文件。类似于直接使用javac命令
下面例子使用JDK1.6 可以编译 String类型的源码
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
/**
* 动态编译JAVA源文件
* @author Vic
*
*/
public class CompilerTest {
public static void main(String[] args) {
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<StringSourceJavaObject> fileObjects = Arrays.asList(sourceObject);
CompilationTask task = compiler.getTask(null, fileManager, null, null, null, fileObjects);
boolean result = task.call();
if(result){
System.out.println("编译成功!");
}else{
System.out.println("编译失败!");
}
}
static class StringSourceJavaObject extends SimpleJavaFileObject{
private String content = null;
protected StringSourceJavaObject(String name, String content) {
super(URI.create("string:///"+name.replace('.', '/')+Kind.SOURCE.extension),Kind.SOURCE);
this.content = content;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors)throws IOException
{
return content;
}
}
}