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);
}
This example covers implementing java interface with javascript. That's also can be used for invocation of javascript callbacks from java.
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]
.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.
Implement an interface: