我正在使用 Rhino 将一些 javascript 嵌入到 Java 应用程序中。我按照 Rhino 网站上的示例,通过调用 Context 的 evaluateString 方法并将实际脚本作为字符串传递来执行脚本。
我有一大堆现有的 javascript 代码,我想使用它们。我不想将它全部连接成一个巨大的字符串并将其传递给 evaluateString。我宁愿能够加载代码,以便我可以从我传递给 evaluateString 的代码中调用它(有点像 AddCode 方法在 Microsoft 的脚本控件中工作)。我想添加代码,就像我目前可以使用 ScriptableObject.putProperty 方法添加变量一样。
有没有办法做到这一点?有人可以提供代码片段或文档链接吗?谢谢!
最佳答案
来自documentation和 examples看起来对以前评估的对象的引用由 scopes 控制.
Context context = Context.enter();
try {
ScriptableObject scope = context.initStandardObjects();
Object out = Context.javaToJS(System.out, scope);
ScriptableObject.putProperty(scope, "out", out);
context.evaluateString(scope,
"function foo() { out.println('Hello, World!'); }", "<1>", 1, null);
context
.evaluateString(scope, "function bar() { foo(); }", "<2>", 1, null);
context.evaluateString(scope, "bar();", "<3>", 1, null);
} finally {
Context.exit();
}
(Rhino 1.7 第 2 版)
我知道有些人直接使用 Rhino 来获取最新版本,但是 Java 6 implementation可以像这样评估脚本:
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
engine.eval("function foo() { println('Hello, World!'); }");
engine.eval("function bar() { foo(); }");
engine.eval("bar();");
关于java - Rhino,从多个javascript文件添加代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3074037/