Intercept script output
suggest changeNashorn is the nashorn engine in Java 8 through 14. It was removed in Java 15. If getEngineByName returns null, the next call throws NullPointerException, not ScriptException.
// Obtain an instance of JavaScript engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
// Setup a custom writer
StringWriter stringWriter = new StringWriter();
// Modify the engine context so that the custom writer is now the default
// output writer of the engine
engine.getContext().setWriter(stringWriter);
// Execute some script
try {
engine.eval("print('Redirected text!');");
} catch (ScriptException ex) {
ex.printStackTrace();
}
// Outcome:
// Nothing printed on standard output, but
// stringWriter.toString() contains 'Redirected text!'
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents