javascript|Java——脚本引擎执行JavaScript代码——Rhino

【javascript|Java——脚本引擎执行JavaScript代码——Rhino】

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Demo1 {
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
//get script engine
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript");

//define
engine.put("msg", "good job!");
String str = "var user = {name:'clare',age:18}; ";
str += "print(user.name); ";

//run
engine.eval(str);
engine.eval("msg = 'clare is good'; ");
System.out.println(engine.get("msg"));

//define method
engine.eval("function add(a,b){var sum = a + b; return sum; }");
//run
Invocable jsInvoke = (Invocable) engine;
Object result = jsInvoke.invokeFunction("add", new Object[] {1,2});
System.out.println(result);

}

}
转载于:https://www.cnblogs.com/CoolClare/p/11316669.html

    推荐阅读