22

Suppose I have a Javascript file

function js_main(args){
     /* some code */
     var x = api_method1(some_argument);
     /* some code */
}

And I try to run it with javax.scripting the usual way

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval(...);

Now the I'd like to handle the call to api_method1 in Javascript with my Java class. I'd like to have some kind of mapping/binding of calls i.e. each time the script calls api_method1(arg) a method

public Object api_method1(Object arg){ ... }

(placed in the same class as the engine) would be called.

Can I achieve this?

1 Answer 1

15
  1. use engine.createBindings() to make a Bindings object;
  2. put an object exposing your method into the bindings with some name:

    Bindings b = engine.createBindings();
    b.put("api", yourApiObject);
    engine.setBindings(b, ScriptContext.ENGINE_SCOPE);
    
  3. Then in JavaScript there'll be a global "api" object you can call:

    api.method1( "foo", 14, "whatever" );
    

The facility is easy to use, but be careful with what you pass back and forth; it doesn't do that much to convert JavaScript types to Java types.

3
  • What about marshaling data to/from the method (besides the primitives)? Commented Jun 20, 2012 at 19:02
  • 1
    to pass data back and forth for other than primitive you can use JSON. Your Java code can serialize/deserialize JSON using any JSON library. Commented Jun 20, 2012 at 19:11
  • 1
    You're pretty much on your own for that. You could serialize to JSON (easy from JavaScript) and then deserialize in Java (less easy, but doable). Or you can expose various utilities to piece together other Java object types. Commented Jun 20, 2012 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.