Java拦截脚本输出
示例
//获取JavaScript引擎的实例 ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("nashorn"); //设置自定义编写器 StringWriter stringWriter = new StringWriter(); //修改引擎上下文,以便自定义编写器现在是默认设置 //引擎的输出编写器 engine.getContext().setWriter(stringWriter); //执行一些脚本 try { engine.eval("print('Redirected text!');"); } catch (ScriptException ex) { ex.printStackTrace(); } //结果: //没有在标准输出上打印任何内容,但是 //stringWriter.toString()包含“重定向文本!”