java生成java文件并动态编译

来源:互联网 发布:网络大电影点击排名 编辑:程序博客网 时间:2024/06/10 17:19

最近,所在项目组要用到动态生成Java 文件并编译执行。百度Google一番,资料还不少。思想就是用类的反射机制来实现。记下自己写成功的代码,以备后用:

 

  1. public void createDynamicFile() throws Exception {
  2.         //得到写文件路径
  3.         String filePath = "D://WorkSpace//code//java//myswt";
  4.         System.out.println("filePath is: "+filePath);
  5.         //得到文件名
  6.         String fileName = "Test";
  7.         File file = new File(filePath);
  8.         //如果目录不存在,则创建目录
  9.         if(!file.exists())
  10.             file.mkdirs();
  11.         String str = "";
  12.         //拼Java文件
  13.         str += "package com.gxg.swtTest; public class Test {public static void t(String[] args){System.out.println(/"Hello World!/");}}";
  14.         //写文件
  15.         OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(filePath + "//" + fileName+".java"),"utf-8");
  16.         out.write(str);
  17.         out.flush();
  18.         out.close();
  19.         
  20.         //动态编译文件
  21.         String className = "Test";
  22.         String path = filePath + "/bin";
  23.         com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
  24.         
  25.         String[] args = new String[] { 
  26.                 "-d",
  27.                 path,
  28.                 "-classpath",
  29.                 "%classpath%;"
  30.                         + path
  31.                         + ";",
  32.                         //包路径
  33. //                      + path+"/persistence-api-1.0.jar;"
  34. //                      + path+"/hibernate-annotations-3.3.0.ga.jar;"
  35. //                      + path+"/hibernate-commons-annotations-3.3.0.ga.jar;"
  36. //                      + path+"/struts2-codebehind-plugin-2.0.11.1.jar;"
  37. //                      + path+"/struts2-core-2.0.11.1.jar;"
  38. //                      + path+"/struts2-spring-plugin-2.0.11.1.jar;"
  39. //                      + path+"/xwork-2.0.4.jar;"
  40. //                      + path+"/spring-orm-2.5.4.jar;"
  41. //                      + path+"/spring-tx-2.5.4.jar;"
  42. //                      + path+"/dom4j-1.6.1.jar;",
  43.                 "-encoding""utf-8", filePath + "//" + fileName +".java" };
  44.         int status = javac.compile(args);
  45.         if(status != 0) {
  46.             System.out.println(fileName + "没有成功编译!"+status);
  47.         } else {
  48.             try {
  49.                 Class cls = Class.forName("Test");
  50.                 // 映射方法
  51.                 Method main = cls.getMethod("t"new Class[] { String[].class });
  52.                 // 执行方法
  53.                 main.invoke(nullnew Object[] { new String[0] }); //第一个参数是方法的对象,第二个是要传入的参数。
  54.             } catch (SecurityException se) {}
  55.         }
  56.     }

OK,现在就可以写个方法来调用测试了。调用createDynamicFile就会看见输出 Hello World!