- 中查找“动态编译实例代码”更多相关内容
- 中查找“动态编译实例代码”更多相关内容
- ·上一篇文章:Java 面试中的陷阱
- ·下一篇文章:ANT安装、配置
动态编译实例代码
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();}
}
}
Tags:
作者:佚名评论内容只代表网友观点,与本站立场无关!
评论摘要(共 0 条,得分 0 分,平均 0 分)
查看完整评论