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
          主站蜘蛛池模板: 于都县| 左贡县| 临泽县| 突泉县| 赫章县| 浦东新区| 河池市| 山阴县| 连江县| 泸州市| 正宁县| 门头沟区| 高邑县| 乌什县| 昌平区| 疏附县| 绵阳市| 扶沟县| 敦化市| 永和县| 福泉市| 永修县| 桓仁| 吴川市| 大石桥市| 彝良县| 通榆县| 宜宾市| 黔西| 东源县| 南木林县| 曲沃县| 赣榆县| 镇康县| 平山县| 陈巴尔虎旗| 阳曲县| 彩票| 体育| 平利县| 合江县|