Reputation: 485
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.
Upvotes: 6
Views: 1801
Reputation: 770
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";
}
Upvotes: 9