服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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);"



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


如有任何问题,请指正!

kingfish

扫描关注微信公众号