java中動態執行一段代碼

來源:互聯網
上載者:User
動態|執行 動態執行一段簡單代碼,採用產生java檔案,調用javac編譯,反射執行的方式。

只是一個簡單測試,有些地方有待完善。

代碼如下



--------------------------------------------------------------------------------


import java.io.*;

/**
* 動態執行一段代碼(組建檔案->編譯->執行)
* @author kingfish
* @version 1.0
*/
public class TestRun {
private String fileName = "Test.java";
private String className= "Test.class";
public TestRun() {
File f = new File(fileName);
if(f.exists()) f.delete();

f = new File(className);
if(f.exists()) f.delete();
}

/**
* 建立java檔案
*/
public void createJavaFile(String body) {
String head = "public class Test{\r\n public static void runCode(){";

String end = "\r\n }\r\n}";
try {
DataOutputStream dos = new DataOutputStream(new FileOutputStream(
fileName));
dos.writeBytes(head);
dos.writeBytes(body);
dos.writeBytes(end);
dos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}

/**
* 編譯
*/
public int makeJavaFile() {
int ret = 0;
try {
Runtime rt = Runtime.getRuntime();
Process ps = rt.exec("cmd /c javac " + fileName);
ps.waitFor();
byte[] out = new byte[1024];
DataInputStream dos = new DataInputStream(ps.getInputStream());
dos.read(out);
String s = new String(out);
if (s.indexOf("Exception") > 0) {
ret = -1;
}
}
catch (Exception e) {
ret = -1;
e.printStackTrace();
}
return ret;
}

/**
* 反射執行
*/
public void run() {
try {
Class.forName("Test").getMethod("runCode", new Class[] {}).invoke(null, new Object[]{});
}
catch (Exception e) {
e.printStackTrace();
}
}

/**
* 測試
*/
public static void main(String[] args) {

String cmd = "System.out.println(\"usage:java TestRun int i=1; System.out.println(i+100);\");";
if(args.length>=1){
cmd = args[0];
}
TestRun t = new TestRun();
t.createJavaFile(cmd);
if (t.makeJavaFile() == 0) {
t.run();
}
}
}




--------------------------------------------------------------------------------


測試:

java TestRun System.out.println(\"Hello,World!\");

java TestRun "int i=1;int j=2;System.out.println(i+j);"



--------------------------------------------------------------------------------


如有任何問題,請指正!

kingfish



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.