Reputation: 99
I have a code which uses Java Swing application for the User Interface but uses JavaScript files to do some hardware testing. Application is calling JavaScript engine to invoke the functions from JavaScript using InvokeFunction()
method.
Now i am using LabJack API which is only available for Java and not for JavaScript. I have a working code (that i implemented separately on Java), but now i need JavaScript to call that Java method.
My question is if there is a way we can invoke Java function from JS code? or in other words, If there is an equivalent way to do this in JS,
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String
String script1 = (String)"function hello(name) {print ('Hello, ' + name);}";
// evaluate script
engine.eval(script1);
Invocable inv = (Invocable) engine;
inv.invokeFunction("hello", "Scripting!!" );
For further explanation i can give a practical example. JavaScript code is calling IR Toy to send IR data to a light. Now i need to collect the number of flashes that light produces. Unfortunately this can only be done using Java (which i have implemented). So now i need to call this Java method from Javascript so that both processes can be in one test.
Upvotes: 1
Views: 1284
Reputation: 159086
The JavaScript engine was changed in Java 8 from the old Rhino to the new Nashorn, and the way to create Java objects was changed.
A generic way that should work in both, would be to pass a Java object to the script using the Bindings
. The JavaScript code can then call any public method of that object.
Alternative, pass it in as a parameter.
EXAMPLE using Bindings
ArrayList<String> myList = new ArrayList<>();
myList.add("Hello");
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("myList", myList);
String script1 = "function hello(name) {" +
" myList.add(name);" +
" print(myList);" +
"}";
engine.eval(script1);
Invocable inv = (Invocable)engine;
inv.invokeFunction("hello", "Scripting!!" );
EXAMPLE using parameter
String script1 = "function hello(myList, name) {" +
" myList.add(name);" +
" print(myList);" +
"}";
engine.eval(script1);
ArrayList<String> myList = new ArrayList<>();
myList.add("Hello");
Invocable inv = (Invocable)engine;
inv.invokeFunction("hello", myList, "Scripting!!");
OUTPUT
[Hello, Scripting!!]
Upvotes: 2