o15a3d4l11s2
o15a3d4l11s2

Reputation: 4059

How to invoke java method from javascript

As described in the title, what I am trying to achieve is the following:

  1. Create java object
  2. Pass it to JavaScript
  3. Invoke a method (a setter for instance) on the passed object
  4. Continue work with the object in java

I am using the scripting included in java. I will be happy if someone can help me with this.

Upvotes: 2

Views: 3894

Answers (1)

Pointy
Pointy

Reputation: 414006

If you're working with the ScriptEngine framework, this is really easy. You can "pass" Java objects to JavaScript in two ways:

  1. You can "seed" the execution environment for JavaScript code and arrange for Java objects to just be "there" in the global namespace
  2. You can pass Java objects in as arguments to JavaScript functions.

You can also access Java constructors from JavaScript and instantiate Java objects if you want.

To do the first thing, you have to set up the "bindings" for the script engine. It's just like a Map:

final Bindings globals = engine.createBindings();
globals.put("foo", yourObject);

Now, when JavaScript code runs in that engine, the global symbol "foo" will serve as a reference to a Java object. You can bind in as many references as you like.

If you want to pass a Java object as a parameter to a JavaScript function, the first thing you need is a way to call a JavaScript function. To do that, you use the "invokeFunction" or "invokeMethod" method exposed by the "Invocable" interface:

final Object result = ((Invocable) engine).invokeMethod(context, methodName, arg, arg, ... );

The "context" there is just a reference to something you want this to refer to in the function that's called. The "methodName" is just a string giving the name of your global JavaScript function.

Java classes are available to the JavaScript environment via their fully-qualified pathnames:

var javaHashMap = new java.util.HashMap();

That would give you a Java HashMap instance as a JavaScript variable.

Upvotes: 5

Related Questions