HelloWorld 善戰者,求之于勢,不責于人;故能擇人而任勢。

          知止而后有定,定而后能靜,靜而后能安,安而后能慮,慮而后能得。物有本末,事有終始。知所先后,則近道矣。

            BlogJava :: 首頁 ::  :: 聯系 ::  :: 管理 ::
            167 隨筆 :: 1 文章 :: 40 評論 :: 0 Trackbacks

          import java.io.File;
          import java.io.FileOutputStream;
          import java.io.PrintWriter;
          import java.lang.reflect.Method;
          import com.sun.tools.javac.Main;

          class ExecJava {
          public static void runJava(String code) {
              File file;
              Main javac = new Main();
              String classname = "";
              String filename = "";
              String path = System.getProperty("user.dir")+"\\work";
              try {
               // 在當前目錄下產生一個臨時JAVA文件
               file = new File(path+"\\TTTTT.java");
               file.createNewFile();
               // 當程序離開時刪除這個臨時文件
               filename = file.getName();
               classname = getClassName(filename);

               // 寫臨時文件
               PrintWriter out = new PrintWriter(new FileOutputStream(file));
               out.print("package com.work;\r\n");
               out.print("public class " + classname + "{\r\n");
               out.print("\tpublic static void main(String[] test) {\r\n");
               out.print("\t\t");
               out.println(code);
               out.println("test();");
               out.println("\t}");
               out.print("\tpublic static void test() {\r\n");
               out.print("\t\t");
               out.println(code);
               out.println("\t}");
               out.println("\r\n}");
               out.flush();
               out.close();
               // 編譯執行臨時文件
               String[] args = new String[] { "-d",path, path+"\\"+ filename };
               int status = javac.compile(args);
               new File(file.getParent(), classname + ".class");
          //     System.out.println(classname);
               System.setProperty("java.class.path", path);
             
               Class clss = Class.forName("com.work.TTTTT");
               System.out.println(clss.getPackage());
               Method m = clss.getMethod("test", null);
               m.invoke(clss,null);
              } catch (Exception e) {
               e.printStackTrace();
               System.out.println(e);
              }
          }

          /** 根據一個java源文件名獲得類名 */
          private static String getClassName(String filename) {
              return filename.substring(0, filename.length() - 5);
          }

          public static void main(String args[]) {
              runJava("System.out.println(\"test\");");
          }
          }



          </script>

          posted on 2007-08-13 18:52 helloworld2008 閱讀(620) 評論(0)  編輯  收藏 所屬分類: java
          主站蜘蛛池模板: 邹平县| 汝阳县| 高陵县| 繁峙县| 刚察县| 永安市| 石门县| 天台县| 枣阳市| 宁城县| 定安县| 建水县| 昂仁县| 天台县| 讷河市| 太白县| 华蓥市| 沂源县| 大悟县| 巢湖市| 平利县| 驻马店市| 东阿县| 大厂| 黔江区| 凉城县| 资兴市| 繁峙县| 长沙县| 永仁县| 虹口区| 榕江县| 军事| 扶风县| 东宁县| 休宁县| 沂源县| 桓台县| 英山县| 景德镇市| 沾化县|