package com.bjsxt.test;
import java.io.FileNotFoundException;
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;
/**
* 测试脚本引擎执行javascript代码
* @author WL20180732
*
*/
public class Demo01 {
public static void main(String[] args) throws ScriptException, NoSuchMethodException, FileNotFoundException {
// 获得脚本引擎对象
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript");
// 定义变量,存储到引擎的上下文中
engine.put("msg", "gaoqi is a good man");
String str = "var user = {name: 'gaoqi', age:18, schools:['清华大学', '北京尚学堂']};";
str += "println(user.name);";
// 执行脚本
engine.eval(str);
engine.eval("msg = 'sxt is a good school';"); // 修改变量
System.out.println(engine.get("msg"));
System.out.println("===============================================================");
// 定义函数
engine.eval("function add(a, b) {var sum = a+b; return sum;}");
// 取得调用接口
Invocable jsInvocable = (Invocable) engine;
// 执行js函数
Object result = jsInvocable.invokeFunction("add", new Object[]{13, 20});
System.out.println(result);
// 导入其他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文件(我们将a.js置于项目的src目录下即可)
URL url = Demo01.class.getClassLoader().getResource("a.js");
FileReader fr = new FileReader(url.getPath());
engine.eval(fr);
try {
if (fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
相关js文件
// 定义方法
function test() {
var a = 3;
var b = 4;
println("invoke js file:" + (a + b));
}
// 调用方法
test();