当前位置导航:炫浪网>>网络学院>>网页制作>>JSP教程

动态编译实例代码

动态编译实例代码。非常简单。我看也不用注解了吧。
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import java.io.File;

public class CompileTest{
static com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
public static void main(String[] args){
try{
File file = File.createTempFile("RunTime",".java",new File(System.getProperty("user.dir")));
String filename = file.getName();
String classname = filename.substring(0,filename.indexOf('.'));
PrintWriter out = new PrintWriter(new FileOutputStream(file));
out.println("public class "+classname+"{");
out.println("public static void main(String[] args){");
out.println("System.out.println(\"Yes!\");");
out.println("}}");
out.flush();
out.close();
String[] arg = new String[]{"-d",System.getProperty("user.dir"),filename};
int status = javac.compile(arg);
Class cls = Class.forName(classname);
Method main = cls.getMethod("main", new Class[]{String[].class} );
main.invoke(null, new Object[] { new String[0] });
file.delete();
file = new File(classname+".class");
file.delete();
}catch(Exception e){e.printStackTrace();}

}
}

相关内容
赞助商链接