spr*_*boy 9 javascript java rhino
基本上我正在尝试将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);
}
Run Code Online (Sandbox Code Playgroud)
实现一个接口:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
sun.org.mozilla.javascript.internal.InterpretedFunction实现接口sun.org.mozilla.javascript.Function.该接口有一个方法,它call需要:
ContextScriptable用作范围Scriptable用作this函数内的值Objects是函数的参数所以,我建议在java中你将你传递的对象转换为a sun.org.mozilla.javascript.Function和call call.前两个参数可以是您从java使用的任何内容,以便首先启动脚本.你在那里使用它的方式,最后两个参数可以是null和new Object[0].