如何将JavaScript函数传递给Java方法以充当回调(Rhino) [英] How can I pass a javaScript function to a Java Method to act as a callback (Rhino)

查看:148
本文介绍了如何将JavaScript函数传递给Java方法以充当回调(Rhino)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我正在尝试将javaScript函数传递给Java方法以充当脚本的回调。

Basically I'm trying to pass a javaScript function to a Java method to act as a callback to the script.

我能做到 - 有点 - 但是我收到的对象是sun.org.mozilla.javascript.internal.InterpretedFunction,我没有看到调用它的方法。

I can do it - sort of - but the object I receive is a sun.org.mozilla.javascript.internal.InterpretedFunction and I don't see a way to invoke it.

有什么想法吗?

这是我到目前为止所拥有的:

Here's what I have so far:

var someNumber = 0;

function start() {
   // log is just an log4j instance added to the Bindings
   log.info("started....");
   someNumber = 20;

    // Test is a unit test object with this method on it (taking Object as a param).
    test.callFromRhino(junk);
}

function junk() {
    log.info("called back " + someNumber);
}


推荐答案

实施界面:

import javax.script.*;

public class CallBack {
  public void invoke(Runnable runnable) {
    runnable.run();
  }

  public static void main(String[] args) throws ScriptException {
    ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js");
    js.getContext().setAttribute("callBack", new CallBack(),
        ScriptContext.ENGINE_SCOPE);
    js.eval("var impl = { run: function () { print('Hello, World!'); } };\n"
        + "var runnable = new java.lang.Runnable(impl);\n"
        + "callBack.invoke(runnable);\n");
  }
}

这篇关于如何将JavaScript函数传递给Java方法以充当回调(Rhino)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆