重定向编译的Nashorn函数中的print()输出

时间:2017-01-22 22:30:24

标签: javascript java nashorn

我正在尝试使用Nashorn从已编译的JavaScript函数中捕获print()输出。在没有专用ScriptEngine

的情况下使用ScriptContext时,这可以正常工作
ScriptEngine engine = new ScriptEngineManager()
        .getEngineByName("nashorn");

// Create a StringWriter for print() output
StringWriter myWriter = new StringWriter();
engine.getContext().setWriter(myWriter);

// Compile the functino in the context.
String code = "function testPrint() {print('Hello World');}";
engine.eval(code);
ScriptObjectMirror fn = (ScriptObjectMirror) engine.getContext()
        .getAttribute("testPrint");

// Call the function and test the output.
fn.call("testPrint");
System.out.println("StringWriter contents: " + myWriter);

输出:

StringWriter contents: Hello World

但是,如果我在隔离的ScriptContext中执行此操作,print()输出始终将转到System.out

ScriptEngine engine = new ScriptEngineManager()
        .getEngineByName("nashorn");

// Set up an isolated context.
Bindings bindings = engine.createBindings();
ScriptContext isolatedContext = new SimpleScriptContext();
isolatedContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

// Create a StringWriter for print() output
StringWriter myWriter = new StringWriter();
isolatedContext.setWriter(myWriter);

// Compile the functino in the context.
String code = "function testPrint() {print('Hello World');}";
engine.eval(code, isolatedContext);
ScriptObjectMirror fn = (ScriptObjectMirror) isolatedContext
        .getAttribute("testPrint");

// Call the function and test the output.
fn.call("testPrint");
System.out.println("StringWriter contents: " + myWriter);

这会产生:

Hello World
StringWriter contents: 

调用函数时,第一行打印到System.out;第二行是代码最后一行的结果,显示StringWriter为空。

如何在手动构建的上下文中编译函数,使其行为类似于使用引擎的默认上下文编译的函数?

1 个答案:

答案 0 :(得分:0)

在使用之前使用SimpleScriptContext的{​​{1}}方法。

public SimpleScriptContext() {
        engineScope = new SimpleBindings();
        globalScope = null;
        reader = new InputStreamReader(System.in);
        writer = new PrintWriter(System.out , true);
        errorWriter = new PrintWriter(System.err, true);
    }

  /** {@inheritDoc} */
    public void setReader(Reader reader) {
        this.reader = reader;
    }

    /** {@inheritDoc} */
    public void setWriter(Writer writer) {
        this.writer = writer;
    }


    /** {@inheritDoc} */
    public void setErrorWriter(Writer writer) {
        this.errorWriter = writer;
    }