|
public class ScriptHost {
private ScriptEngine _engine;
ScriptHost(ScriptEngine engine){
this._engine = engine;
}
/**
* 创建一个脚本执行环境
* @param context
* @return
* @throws ScriptException
*/
public static ScriptHost createHost(ScriptExecutionContext context) throws ScriptException {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByMimeType("text/javascript");
if (engine == null) {
throw new ScriptException("new ScriptEngine fail.");
}
engine.put("cox",context);
engine.eval("function require(path){var script = cox.loadScript(path) + ';';return eval(script.toString());};");
return new ScriptHost(engine);
}
/**
* 执行脚本
*
* @param script
* @param parameters
* @return
* @throws ScriptException
* @throws NoSuchMethodException
*/
public Object execute(String script, Object parameters) throws ScriptException, NoSuchMethodException {
_engine.eval(script);
Invocable inv = (Invocable) _engine;
return inv.invokeFunction("execute", parameters);
}
} |
|