繁体   English   中英

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

[英]Using Rhino, how can I set a Java object as the global scope for executing JS code?

我有一段要在全局范围内的Java对象上执行的JS代码。 我试图让我的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].

我有一个类似的代码,并且我正在使用此代码:

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

...

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

我的JS看起来像这样:

commands.log("Test");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM