Reputation: 4059
As described in the title, what I am trying to achieve is the following:
I am using the scripting included in java. I will be happy if someone can help me with this.
Upvotes: 2
Views: 3894
Reputation: 414006
If you're working with the ScriptEngine framework, this is really easy. You can "pass" Java objects to JavaScript in two ways:
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