国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

java中動態執行一段代碼

2019-11-18 14:29:37
字體:
來源:轉載
供稿:網友

  動態的執行一段簡單代碼,采用生成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();
}
}
}




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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 韶山市| 科技| 道孚县| 墨玉县| 河曲县| 南澳县| 桓台县| 扬中市| 衡阳市| 福泉市| 五莲县| 寻甸| 伊川县| 桐城市| 宁津县| 明溪县| 桃江县| 确山县| 兴仁县| 家居| 柞水县| 汉寿县| 文化| 微山县| 兴隆县| 玛多县| 黄梅县| 秦皇岛市| 南丰县| 堆龙德庆县| 莱芜市| 枞阳县| 鄂尔多斯市| 香港 | 曲周县| 广饶县| 德州市| 和静县| 江源县| 荣成市| 大城县|