使用Rhino,如何将Java对象设置为执行JS代码的全局范围?

时间:2015-02-03 15:34:51

标签: java javascript rhino

我有一段JS代码,我想用Java对象作为全局范围来执行。我尝试让我的Java对象扩展ScriptableObject并运行context.initStandardObjects(this),但没有运气(不太确定我在做什么)。

public Foo extends ScriptableObject {

  @JSFunction
  public int getBar() {
    return 42;
  }

  public void run() {
    Context cx = Context.enter();
    Scriptable scope = cx.initStandardObjects(this);
    cx.evaluateString(scope, source, "script", 0, null);
    Function fct = (Function) scope.get("run", scope);
    fct.call(cx, scope, scope, new Object[0]);
    Context.exit();
  }
}

虽然我的JS代码是:

function run() {
  console.log(this.getBar());
}

然而,当运行foo.run()时,我得到一个异常,说明函数getBar()不存在。这可能意味着Foo没有被设置为全球范围。

有人能指出我正确的方向吗?

编辑:更具描述性的错误消息:

org.mozilla.javascript.EcmaError: TypeError: Cannot find function getBar in object [object Foo].

1 个答案:

答案 0 :(得分:0)

我有类似的代码,我正在使用它:

ScriptableObject.putProperty(mScope, "commands", Context.javaToJS(new Commands(), mScope));
mContext.evaluateString(mScope, ...);

...

public class Commands {
    public void log(String text) {
        ...
    }
}

我的JS看起来像这样:

commands.log("Test");