Реальный пример на этот раз, т.е. запуск парсера esprima с Rhino 1.7R4.
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
...
Context context = Context.enter();
Scriptable globalScope = context.initStandardObjects();
Reader esprimaLibReader = new InputStreamReader(getClass().getResourceAsStream("/esprima.js"));
context.evaluateReader(globalScope, esprimaLibReader, "esprima.js", 1, null);
// Add a global variable out that is a JavaScript reflection of the System.out variable:
Object wrappedOut = Context.javaToJS(System.out, globalScope);
ScriptableObject.putProperty(globalScope, "out", wrappedOut);
String code = "var syntax = esprima.parse('42');" +
"out.print(JSON.stringify(syntax, null, 2));";
// The module esprima is available as a global object due to the same
// scope object passed for evaluation:
context.evaluateString(globalScope, code, "<mem>", 1, null);
Context.exit();
После запуска этого кода вы должны увидеть вывод следующим образом:
{
"type": "Program",
"body": [
{
"type": "ExpressionStatement",
"expression": {
"type": "Literal",
"value": 42,
"raw": "42"
}
}
]
}
Так что, действительно, хитрость заключается в повторном использовании объекта globalScope
.