Piero
Piero

Reputation: 189

javax.script pass to javascript a Java method to use as a callback

I'm using javax.script to embed javascript code to a Java method.

In my project the javascript takes care to send asynchronous http request through a websocket. Once a response is received I need to execute a callback function.

I would like to invoke a method written in Java as a callback.

In the documentation here: http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/ it is explained how to implement java methods in javascript for an interface, but not how to invoke Java methods form javascript.

Thanks

Upvotes: 2

Views: 1895

Answers (2)

mogsie
mogsie

Reputation: 4156

Use a Function in Java 8:

JS:

run = function(callback) {
  callback("foo");
}

Java:

Function<String,String> fn = (arg) -> {
  return arg.toUpperCase();
};

// call run(fn)
invokeFunction("run", fn)

You can also use Runnable (no arguments or return values) and probably many other single-method interfaces as callback interfaces. From what I undertand it will try to find a method that matches the argument list dynamically.

Presumably you can use this to bind functions to the scope too.

Upvotes: 1

cmbaxter
cmbaxter

Reputation: 35453

Not sure if this is exactly what you are looking for, but here is a code sample that supplies a java object callback into some javascript code that will then call back on that callback later:

public class JsCallback{
  public static void main(String[] args) throws Exception{

   ScriptEngineManager factory = new ScriptEngineManager();
   ScriptEngine engine = factory.getEngineByName("JavaScript");
   engine.put("cb", new JsCallback());
   engine.eval("println('Doing something in javascript here first');" +
     "cb.apply('bar');");
  }

  public void apply(String s){
    System.out.println("Back in java code here: " + s);
  }
}

Upvotes: 1

Related Questions