基本上我试图将一个
javaScript函数传递给一个
Java方法,作为脚本的回调.
我可以这样做 – 但是我收到的对象是一个sun.org.mozilla.javascript.internal.InterpretedFunction,我没有看到一种方法来调用它.
有任何想法吗?
这是我到目前为止
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"); } }