如何将 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);
}
Basically I'm trying to pass a javaScript function to a Java method to act as a callback to the script.
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.
Any ideas?
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实现一个接口:
Implement an interface:
sun.org.mozilla.javascript.internal.InterpretedFunction
实现接口sun.org.mozilla.javascript.Function
。该接口有一个名为call
的方法,它需要:Context
Scriptable
Scriptable
> 在函数中使用作为函数Objects
数组作为this
的值所以,我建议在java中你转换你的对象作为sun.org.mozilla.javascript.Function
传递并调用call
。前两个参数可以是您最初在 java 中用于启动脚本的任何参数。按照您在那里使用它的方式,最后两个参数可以是null
和new Object[0]
。sun.org.mozilla.javascript.internal.InterpretedFunction
implements the interfacesun.org.mozilla.javascript.Function
. That interface has a method on it calledcall
that takes:Context
Scriptable
to use as the scopeScriptable
to use as the value ofthis
within the functionObjects
that are the arguments to the functionSo, what I suggest is that in java you cast the object you were passed as a
sun.org.mozilla.javascript.Function
and callcall
. The first two arguments can be whatever you used from java to start the script in the first place. The way you're using it there, the last two arguments can benull
andnew Object[0]
.解决方案实际上是在另一个脚本中调用它。这种工作方式是这样的:
当您取回对函数的引用时,您需要要求引擎为您执行该函数。虽然不太漂亮,但要求 js 使用一组特定的绑定来 eval() 它实际上会为你完成这项工作。您需要注意您正在操作的变量属于正确的范围;我想这里很容易犯错误。
The solution is actually to invoke it in another script. This sort of works:
When you get back the reference to a function, you need to ask the engine to execute that function for you. And although not pretty, asking js to eval() it for you with a specific set of bindings will actually do the job for you. You need to take care that the variables you're manipulating belong to the right scope; I guess it's easy to make mistakes here.
此示例涵盖使用 javascript 实现 java 接口。这也可以用于从 java 调用 javascript 回调。
This example covers implementing java interface with javascript. That's also can be used for invocation of javascript callbacks from java.