编译器 源代码,动态编译实例代码

动态编译实例代码 - 电脑技巧 - 电脑教程网

动态编译实例代码

日期:2006-11-18   荐:
动态编译实例代码。非常简单。我看也不用注解了吧。
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();}

}
}

(出处:http://www.sheup.com)




标签: