來源:http://www.bjsxt.com/
一、S02E215_01腳本引擎執行javascript代碼_Rhino引擎
package com.test.rhino;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
* 測試腳本引擎Rhino執行javascript代碼
*/
public class Demo {
public static void main(String[] args) throws ScriptException, NoSuchMethodException, IOException {
//獲取腳本引擎對象
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript");//或"js"
//定義變量,存儲到引擎上下方中,java和javascript都可獲取
engine.put("msg", "test is a good man!");
String str = "var user = {name:'test',age:18,shcools:['清華','北大']};";
str += "print(user.name);";
//執行腳本
engine.eval(str);
engine.eval("msg = 'beida is a godd school';");//javascript修改變量值
System.out.println(engine.get("msg"));
System.out.println("###############################");
//定義函數
engine.eval("function add(a,b){var sum = a + b; return sum;}");
//取得調用接口
Invocable jsInvoke = (Invocable) engine;
//執行腳本中定義的方法
Object result1 = jsInvoke.invokeFunction("add", new Object[]{13,20});
System.out.println(result1);
//導入其它java包,使用其它包中的java類
//注:本例所用的環境java8已不支持Rhino,已改爲Nashorn。添加腳本:load(\"nashorn:mozilla_compat.js\"); 運行
String jsCode = "load(\"nashorn:mozilla_compat.js\"); importPackage(java.util); var list = Arrays.asList([\"北大\",\"清華\",\"復旦\"]);";
engine.eval(jsCode);
List<String> list2 = (List<String>) engine.get("list");
for (String temp : list2) {
System.out.println(temp);
}
//執行js文件(a.js放到項目src下)
URL url = Demo.class.getClassLoader().getResource("a.js");
FileReader fr = new FileReader("g:/java/test/a.js");//(url.getPath());
engine.eval(fr);
fr.close();
}
}
控制檯輸出:
test
beida is a godd school
###############################
33
北大
清華
復旦
invoke js file:7