58,452
社区成员




package wmw.run.view;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author Every E-mail/MSN:mwgjkf@hotmail.com
* QQ:30130942
* @version 创建时间:Dec 30, 2008 3:34:57 PM
* 类说明:
*
*/
public class RuntimeCode{
/**编译器*/
private static com.sun.tools.javac.Main javac=new com.sun.tools.javac.Main();
/**等待用户输入JavaCode,然后编译、执行*/
public static void main(String[] args) throws Exception{
String code = "for(int i=0;i<10;i++){System.out.println(i);}";
// 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.println(code);
}
/**编译JavaCode,返回临时文件对象*/
private synchronized static File compile(String code)throws IOException,Exception{
File file;
//在用户当前文件目录创建一个临时代码文件
file=File.createTempFile("JavaCode",".java",new File(System.getProperty("user.dir")));
//当虚拟机退出时,删除此临时java源文件
file.deleteOnExit();
//获得文件名和类名字
String filename=file.getName();
String classname=getClassName(filename);
System.out.println(classname);
//将代码输出到文件
PrintWriter out=new PrintWriter(new FileOutputStream(file));
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){
//当虚拟机退出时,删除此临时编译的类文件
//获得文件名和类名字
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.invoke(null, new Object[] { new String[0] });
}catch (SecurityException se) {
debug("access to the information is denied:" + se.toString());
}catch (NoSuchMethodException nme) {
debug("a matching method is not found or if then name is or : " + nme.toString());
}catch (InvocationTargetException ite) {
debug("Exception in main: " + ite.getTargetException());
}catch (Exception e){
debug(e.toString());
}
}
/**打印调试信息*/
private static void debug(String msg){
System.err.println(msg);
}
/**根据一个java源文件名获得类名*/
private static String getClassName(String filename){
return filename.substring(0,filename.length()-5);
}
}