简体   繁体   中英

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

I have a piece of JS code that I want to execute with a Java object being the global scope. I tried having my Java object extend ScriptableObject and running context.initStandardObjects(this) but no luck (not really sure what I'm doing).

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();
  }
}

While my JS code is:

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

When running foo.run() however, I get an exception stating that the function getBar() does not exist. Which probably means that Foo is not being set as the global scope.

Can anyone point me in the right direction?

Edit: A more descriptive error message:

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

I have a similar code, and I am using this:

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

...

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

My JS looks like this:

commands.log("Test");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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