开发一个工具类,该工具类提供一个eval方法,实现javascript函数的eval功能

package load;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class EvalTest {

/**
* @param args
* @throws Exception
*/
//
public static void eval(String str) throws Exception{
File file = new File("D:\201105\java\src\load\Eval.java");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter ow = new OutputStreamWriter(fos);
PrintWriter pw = new PrintWriter(ow);
BufferedWriter bw = new BufferedWriter(ow);
StringBuilder sb = new StringBuilder();
sb.append("public class Eval{");
sb.append("public void eval(){");
sb.append(str);
sb.append("}");
sb.append("}");
pw.write(sb.toString());
pw.close();
}

public static void main(String[] args) {
// TODO Auto-generated method stub
try {
eval("System.out.println("eval 测试成功了,可以去asfd吃饭了");");
Class eval = Class.forName("load.Eval");
Method me = eval.getDeclaredMethod("eval", null);
me.invoke(eval.newInstance(), null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

发表评论