import java.io.*;
import java.lang.reflect.Method;
import com.sun.tools.javac.*;
public class RuntimeCode {
private static Main javac = new Main();
/**等待用戶輸入JavaCode,然後編譯、執行*/
public static void main(String[] args) throws Exception {
String code = "";
DataInputStream bd = new DataInputStream(System.in);
byte[] brray= new byte[200];
int i = bd.read(brray);
code = new String(brray,0,i);
run(compile(code));
System.out.print(code);
}
/**編譯JavaCode,返回暫存檔案物件*/
private synchronized static File compile(String code) throws Exception {
File file;
//在用戶當前文件目錄創建一個臨時代碼文件
file = File.createTempFile("JavaRuntime", ".java", new File(System.getProperty("user.dir")));
System.out.println(System.getProperty("user.dir"));
//當虛擬機退出時,刪除此臨時java原始檔案
//file.deleteOnExit();
//獲得檔案名和類名字
String filename = file.getName();
String classname = getClassName(filename);
//將代碼輸出到文件
PrintWriter out = new PrintWriter(new FileOutputStream(file));
// out.println("/**");
out.write("class "+classname+"{"+"public static void main(String[] args)"+"{");
out.write(code);
out.write("}}");
//關閉文件流
out.flush();
out.close();
String[] args = new String[] { "-d", System.getProperty("user.dir"),filename };
//返回編譯的狀態代碼
int status = javac.compile(args);
System.out.println(status);
return file;
}
//運行程序
private static synchronized void run(File file) throws Exception {
String filename = file.getName();
String classname = getClassName(filename);
//當虛擬機退出時,刪除此臨時編譯的類文件
new File(file.getParent(),classname + ".class").deleteOnExit();
try {
Class cls = Class.forName(classname);
//映射main方法
Method main = cls.getMethod("main", new Class[] { String[].class });
//執行main方法
main.invoke(null, new Object[] { new String[0] });
} catch (SecurityException se) {
}
}
private static void debug(String msg) {
System.err.println(msg);
}
private static String getClassName(String filename) {
return filename.substring(0, filename.length() - 5);
}
}
本文地址:http://com.8s8s.com/it/it12348.htm