I want to call the Javascript inside my Java class but not able to find correct way. I read somewhere it can be done using Nashorn. could someone please let me know the exact way.
Nashorn: Nashorn is a JavaScript engine which is introduced in JDK 8. With the help of Nashorn, we can execute JavaScript code at Java Virtual Machine. Nashorn is introduced in JDK 8 to replace existing JavaScript engine i.e. Rhino.
The Nashorn parser API enables applications, in particular IDEs and server-side frameworks, to parse and analyze ECMAScript code. Parse ECMAScript code from a string, URL, or file with methods from the Parser class.
Calling JavaScript from JavaTo call Nashorn JavaScript from a Java 8 program, you basically need to make a new ScriptEngineManager instance and use that ScriptEngineManager to load the Nashorn script engine by name.
You can call JavaScript using "ScriptEngineManager" as below.
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine engine = scriptEngineManager.getEngineByName("nashorn");
try {
engine.eval(new FileReader("src\\demo.js"));
Invocable invocable = (Invocable)engine;
Object result = invocable.invokeFunction("fun1", "User");
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
And you JS file demo.js will looks something like below.
var fun1 = function(name){
print('Hi,'+name);
return "Greeting from javascript";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With