Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute JavaScript file in Java8 using Nashorn

Tags:

java-8

nashorn

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.

like image 577
Sumit Sood Avatar asked May 08 '18 11:05

Sumit Sood


People also ask

What is Nashorn JavaScript engine in Java 8?

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.

What is the use of Nashorn JavaScript engine?

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.

Can JavaScript code can be executed from Java 8 code base?

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.


1 Answers

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";
}
like image 118
surendrapanday Avatar answered Oct 06 '22 22:10

surendrapanday