首 页 | 网页模板 | 教程 | 源码下载 | 书籍下载 | 图片素材 | 字体 | JAVA特效 | FLASH源码 | 软件 | 矢量 | 论坛 | 其它 |
设为主页
加入收藏
联系站长
平面设计 | 网页制作 | 程序编写 | 数 据 库 | 媒体动画 | 网络冲浪 | 服务器相关 |
当前在线
广告:P4服务器电信机房6999/年即送产权 | 疾风下载
java中动态执行一段代码
2005-4-8 7:38:36  作者:模板天下收集整理  来源:未知 网友评论 0 条 论坛
  动态的执行一段简单代码,采用生成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页  [1] 
>> 相关文章

关于网站 | 客服中心 | 服务条款 | 友情链接 | 广告联系 | 本站历程 | 网站导航

吉ICP备05000107号