Java脚本引擎操作JSDemo
package ScriptEngineTest;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileReader;
import java.net.URL;
import java.util.List;
public class Demo01 {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager=new ScriptEngineManager();
ScriptEngine engine=manager.getEngineByName("javascript");
engine.put("msg","lqs");
String str="var user={name:'lqs',age:18};";
str += "print(user.name);";
engine.eval(str);
engine.eval("msg='ybb'");
System.out.println(engine.get("msg"));
engine.eval("function add(a,b){var sum=a+b;return sum;}");
Invocable jsInvoke = (Invocable)engine;
Object result=jsInvoke.invokeFunction("add",new Object[]{13,20});
System.out.println(result);
String jscode="var list=java.util.Arrays.asList([\"lqsbb\",\"ybbmm\"]);";
engine.eval(jscode);
List<String> list=(List<String>)engine.get("list");
for(String s:list){
System.out.println(s);
}
URL url=Demo01.class.getClassLoader().getResource("ScriptEngineTest/a.js");
FileReader fr=new FileReader(url.getPath());
engine.eval(fr);
fr.close();
}
}