動態編譯JAVA代碼並執行

來源:互聯網
上載者:User

標籤:img   input   write   row   ack   get   test   java代碼   out   

 

package com.bjsxt.test;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.Writer;import javax.tools.JavaCompiler;import javax.tools.ToolProvider;public class Test { public static void main(String[] args) throws IOException {      //通過IO流操作,將字串儲存成一個臨時檔案(Hi.java),然後調用動態編譯方法!         String str = "public class Hi {public static void main(String[] args){System.out.println(\"HaHa,sxt!\");}}";       File file=new File("D://Hi.java");       writeFile(file,str);       JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();        int result = compiler.run(null, null, null, "D://Hi.java");        System.out.println(result==0?"編譯成功":"編譯失敗");                        //通過Runtime調用執行類      Runtime run = Runtime.getRuntime();        Process process = run.exec("java -cp  D://  Hi");           InputStream in = process.getInputStream();     BufferedReader reader = new BufferedReader(new InputStreamReader(in));     String info = "";     while((info=reader.readLine())!=null){        System.out.println(info);    }                /* try {          URL[] urls = new URL[] {new URL("file:/"+"C:/myjava/")};          URLClassLoader loader = new URLClassLoader(urls);          Class c = loader.loadClass("HelloWorld");          //調用載入類的main方法          Method m = c.getMethod("main",String[].class);          m.invoke(null, (Object)new String[]{});          //由於可變參數是JDK5.0之後才有。          //m.invoke(null, (Object)new String[]{});會編譯成:m.invoke(null,"aa","bb"),就發生了參數個數不匹配的問題。          //因此,必須要加上(Object)轉型,避免這個問題。          //public static void main(String[] args)                } catch (Exception e) {          e.printStackTrace();      }    */  }   private static void writeFile(File file,String str) throws IOException {     //1.定義字元輸出資料流對象     Writer fw=new FileWriter(file);     BufferedWriter bw=new BufferedWriter(fw);          //2.按行寫入     bw.write(str);     bw.newLine();     bw.write("//我愛你");     bw.flush();          //3.關閉流     fw.close();     System.out.println("寫入成功");      } }
denamicCompile

 

動態編譯JAVA代碼並執行

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.