java 动态编译与用Rhino引擎执行javascript代码

时间:2021-10-23 18:13:52

动态编译

/**
* 动态编译
* @author L J
*/

@SuppressWarnings("all")
public class TestCompile {
public static void main(String[] args) {
String str = "public class Compile {public static void main(String[] args) {System.out.println(\"hello world!\");}}";
try {
//将字符串输出到文件中
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:/DB/Compile.java")));
writer.write(str);
writer.flush();
writer.close();

//动态编译
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, "F:/DB/Compile.java");
System.out.println(result == 0 ? "编译成功" : "编译失败");

/*1、通过RunTime动态运行
Runtime run = Runtime.getRuntime();
Process process = run.exec("java -cp F:/DB Compile");

//获取输出结果
InputStream in = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String info = "";
while((info = reader.readLine()) != null) {
System.out.println(info); //hello world!
}*/


//2、通过URLClassLoader加载编译好的文件,利用反射运行main方法
URL[] urls = new URL[]{new URL("file:/" + "F:/DB/")};
URLClassLoader loader = new URLClassLoader(urls);
Class c = loader.loadClass("Compile");
//调用加载类的main方法
Method m = c.getMethod("main", String[].class);
//由于可变参数是JDK5.0之后才有的,所以会被编译成:m.invoke(null, "aa", "bb"),会发生参数不匹配的问题
//所以强制转换成Object类型
m.invoke(null, (Object)new String[]{"aa", "bb"});
} catch (Exception e) {
e.printStackTrace();
}
}
}

用脚本引擎执行javascript代码

/**
* 测试脚本引擎执行javascript代码
* @author L J
*/

@SuppressWarnings("all")
public class JavaScriptEngine {
public static void main(String[] args) throws Exception {
//获得脚本引擎对象
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript");

//定义变量(即可以被js操作,又可以被java操作),存储到引擎上下文中
engine.put("msg", "that's why you go away!");
String str = "var user = {name:'小明', age:18, schools:['清华大学', '北京大学']};";
str += "println(user.name)"; //println只能打印在java控制台

//执行脚本
engine.eval(str); //小明
engine.eval("msg = 'baby!'");
System.out.println(engine.get("msg")); //baby!

//定义函数
engine.eval("function add(a, b) {var sum = a + b; return sum}");
//取得调用接口
Invocable jsInvoke = (Invocable) engine;
Object result = jsInvoke.invokeFunction("add", new Object[]{12, 23});
System.out.println(result); //35.0

//导入其他java包、使用其他包中的java类
String jsCode = "importPackage(java.util);" +
"var list = Arrays.asList([\"清华大学\", \"北京大学\", \"浙江大学\"]);";
engine.eval(jsCode);

List<String> list = (List<String>) engine.get("list");
for(String temp : list) {
System.out.println(temp);
}

//执行一个js文件(以下需要将js文件置于项目的src目录下)
URL url = JavaScriptEngine.class.getClassLoader().getResource("test.js");
FileReader fr = new FileReader(url.getPath());
engine.eval(fr);
fr.close();
}
}