最近,所在项目组要用到动态生成Java 文件并编译执行。百度Google一番,资料还不少。思想就是用类的反射机制来实现。记下自己写成功的代码,以备后用:
- public void createDynamicFile() throws Exception {
- //得到写文件路径
- String filePath = "D://WorkSpace//code//java//myswt";
- System.out.println("filePath is: "+filePath);
- //得到文件名
- String fileName = "Test";
- File file = new File(filePath);
- //如果目录不存在,则创建目录
- if(!file.exists())
- file.mkdirs();
- String str = "";
- //拼Java文件
- str += "package com.gxg.swtTest; public class Test {public static void t(String[] args){System.out.println(/"Hello World!/");}}";
- //写文件
- OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(filePath + "//" + fileName+".java"),"utf-8");
- out.write(str);
- out.flush();
- out.close();
- //动态编译文件
- String className = "Test";
- String path = filePath + "/bin";
- com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
- String[] args = new String[] {
- "-d",
- path,
- "-classpath",
- "%classpath%;"
- + path
- + ";",
- //包路径
- // + path+"/persistence-api-1.0.jar;"
- // + path+"/hibernate-annotations-3.3.0.ga.jar;"
- // + path+"/hibernate-commons-annotations-3.3.0.ga.jar;"
- // + path+"/struts2-codebehind-plugin-2.0.11.1.jar;"
- // + path+"/struts2-core-2.0.11.1.jar;"
- // + path+"/struts2-spring-plugin-2.0.11.1.jar;"
- // + path+"/xwork-2.0.4.jar;"
- // + path+"/spring-orm-2.5.4.jar;"
- // + path+"/spring-tx-2.5.4.jar;"
- // + path+"/dom4j-1.6.1.jar;",
- "-encoding", "utf-8", filePath + "//" + fileName +".java" };
- int status = javac.compile(args);
- if(status != 0) {
- System.out.println(fileName + "没有成功编译!"+status);
- } else {
- try {
- Class cls = Class.forName("Test");
- // 映射方法
- Method main = cls.getMethod("t", new Class[] { String[].class });
- // 执行方法
- main.invoke(null, new Object[] { new String[0] }); //第一个参数是方法的对象,第二个是要传入的参数。
- } catch (SecurityException se) {}
- }
- }
OK,现在就可以写个方法来调用测试了。调用createDynamicFile就会看见输出 Hello World!