src下a.js
function test(){
var arr = [1, 2, 3, 4, 7];
for(i in arr){
print(arr[i]);
}
}
test();
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
import java.net.URL;
import java.util.List;
/**
* 测试脚本引擎执行JavaScript代码
*/
public class Demo01 {
public static void main(String[] args) throws Exception{
// 获得脚本引擎对象
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript");
// 定义变量, 存储到引擎上下文中
engine.put("msg", "this is a string");
String str = "var user = {name: 'xiaobo', age: 19};";
str += "print(user.name);";
// 执行脚本
engine.eval(str);
engine.eval("msg = 'Hello World'");
System.out.println(engine.get("msg"));
engine.eval("print(eval('9+3+4*5'))");
// 定义函数
engine.eval("function add(a, b){var sum = a + b; return sum;}");
// 执行js代码
// 1.
Invocable jsInvoke = (Invocable)engine;
Object result1 = jsInvoke.invokeFunction("add", new Object[]{
13, 20});
System.out.println(result1);
// 2.
engine.eval("for(var i=0;i<10;i++) print(add(1+i,3+i));");
// 导入其他java包, 使用其他包中的java类
String jsCode = "var list = java.util.Arrays.asList([\"java\",\"python\",\"c\"]);";
engine.eval(jsCode);
List list2 = (List<String>)engine.get("list");
System.out.println(list2);
// 执行js文件(src 下)
URL url = Demo01.class.getClassLoader().getResource("a.js");
FileReader fr = new FileReader(url.getPath());
engine.eval(fr);
fr.close();
}
}