java - 在 Rhino Javascript 中共享 java 对象

标签 java javascript rhino

首先我要承认我是 JavaScript 菜鸟。因此,这个问题的基础知识可能不太完善,并且可能缺乏足够的信息来帮助我。

背景

我的组织有一个内部基于 Eclipse 的 JavaScript IDE。我们所要做的就是用 JavaScript 编写脚本并直接执行它们。我的猜测是它使用了 Rhino,因为我在一些异常的堆栈跟踪中看到了它。

我的代码运行在 3 个“.js”文件中。

Script-1:声明全局变量并将其实例化为 Java 对象

importClass(java.util.HashMap);
var hmTCResult = new HashMap();

Script-2:使用 Script-1 中的全局变量执行一些操作

Script-2.prototype.run = function() {
hmTCResult.put("Result", "Fail");
};

changeStatus = function(strStatus){
hmTCResult.put("Result", strStatus);
};

Script-3:调用 Script-2 中使用全局变量的函数

changeStatus("Pass") 

问题定义

当我从 Script-3 调用 Script-2 中的函数时,它似乎没有选择实例变量,并且我的函数失败,即我收到异常“hmTCResult 未设置为对象的实例”。请注意,相同的变量 hmTCResult 在脚本 1 中运行良好。

我已经阅读了 JavaScript 中的作用域和上下文,但无法突破它,因为我没有在 IDE 中明确地看到它。

如果需要,我很乐意提供更多信息。

最佳答案

这很好用,只需调整你的范围并设置原型(prototype)搜索即可:

Context cx = Context.enter();
try {
    // Cache and reuse:
    ScriptableObject sealedSharedScope = cx.initStandardObjects(null,
            true);
    // Force the LiveConnect stuff to be loaded.
    String loadMe = "RegExp; getClass; java; Packages; JavaAdapter;";
    cx.evaluateString(sealedSharedScope, loadMe, "preLoadLazyLoad", 0,
            null);

    cx.evaluateString(sealedSharedScope, "varInRoot = 'blah';",
            "setVarInRoot", 0, null);

    // here you can put more cx.evaluateString calls to set up your
    // environment (eg. hmTCResult)

    // now connect a throw-away new scope into the hierarchy, with local
    // vars:
    Scriptable scope = cx.newObject(sealedSharedScope);
    // ensure that definitions in the root scope are found
    scope.setPrototype(sealedSharedScope);
    // ensure that new global variables are created in this scope (don't
    // use
    // var for them!)
    scope.setParentScope(null);

    cx.evaluateString(scope, "localVar = varInRoot;", "mySource", 0,
            null);
    assertEquals("blah", scope.get("localVar", scope).toString());
    // new var not in root:
    assertEquals(ScriptableObject.NOT_FOUND,
            sealedSharedScope.get("localVar", scope));
} finally {
    Context.exit();
}

请注意,scope.get 不会搜索原型(prototype)链 - 必须自己执行此操作!

作用域独立于 Context 并且在 Context.exit() 后仍然存在。

关于java - 在 Rhino Javascript 中共享 java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999095/

相关文章:

java - 在 main 方法中访问变量

java - 如何降低JAVA应用的CPU使用率?

javascript - Google 表格中的列数? VBA 为例

javascript - angularjs 使用多个数组以 json 格式将数据发送到 mvc Controller

javascript - 设置按下按钮的最大次数

python - 如何通过具有相同索引对子列表进行分组?

java - SQL + JPA : return rows with maximum value of single column

java - Nashorn 和 Rhino : Splitting strings by whitespace regexp

java - Rhino,从多个javascript文件添加代码

java - hbase dns 连接错误或可能是 ipv6