在java中动态执行一段代码

 

动态的执行一段简单代码,采用生成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);"

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值