package com.example.ee;
import org.json.JSONArray;
import org.json.JSONException;
import org.junit.Test;
import org.json.JSONObject;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class G {
@Test
public void pp() throws Exception {
ScriptEngineManager sem=new ScriptEngineManager();
ScriptEngine js = sem.getEngineByName("javascript");
js.put("msg","bye");
js.eval("var a=[1,{'b':[3,2]}];"); //可以定义对象(list)
String str="function f(x){print(a[1]['b'][1]);return x+'good'+msg}";
Object eval = js.eval(str+";f(3)");
System.out.println("eval="+eval); //2 eval=3goodbye
//另一种调用js的function的方法
Invocable ia=(Invocable)js;
Object f = ia.invokeFunction("f",2);
System.out.println("f="+f); //2 f=2goodbye
js.eval("var b=[3,4];var bb=JSON.stringify(b);");
js.eval("var c={'c1':'c2'};var cc=JSON.stringify(c);");
String bb = (String)js.get("bb");
String cc = (String)js.get("cc");
//jsonArray和jsonObject分别和java的List和Map非常像
JSONArray jsonArray = new JSONArray(bb);
JSONObject jsonObject = new JSONObject(cc);
//[3,4] 3
System.out.println(jsonArray+"\t"+jsonArray.get(0));
//{"c1":"c2"} c2
System.out.println(jsonObject+"\t"+jsonObject.get("c1"));
//执行js文件,把1.js放在项目的src(resources)文件夹下
//1.js的内容是print(123);貌似不识别console.log和let
URL url = this.getClass().getClassLoader().getResource("1.js");
FileReader fileReader = new FileReader(url.getPath());
//123 null
System.out.println(js.eval(fileReader));
fileReader.close();
}
}
js对象/数组不能直接传给java,否则获得object。所以使用了json字符串传递。也可以用如下方法,未测试: