How to run JavaScript embedded in java program using Nashorn JavaScript Engine??

 Nashorn JavaScript Engine

              It is a JavaScript engine introduced in java8. It was developed by oracle. Now, it is under the OpenJDK community.

Purpose:

This is used to run the JavaScript code in JVM (Java Virtual Machine).

Why Nashorn?

It is efficient in execution compared to previous one (Rhino Engine).

It easily integrates java and JavaScript. The user can simply use the command line.

How to run JavaScript embedded in java program using Nashorn JavaScript Engine??

              Here, java Script is a single line which displays a greetings “Happy Programming”.

Steps:

  • Import three built in packages from javax.script(.ScriptEngine,.ScriptEngineManager,.ScriptException)
  • Create a public class NashornEg and save the file as “NashornEg.java”
  • Inside the main() function,create an object for ScriptEngineManager as mgr.
  • Get the Nashorn script Engine.
  • Write a java script code.
  • Eval the script by Object result1 = engine1.eval(script);
  • Print the result.

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

public class NashornEg {

    public static void main(String[] args) {

        // Create an object for ScriptEngineManager

        ScriptEngineManager mgr = new ScriptEngineManager();

       // find the Nashorn script engine

        ScriptEngine engine1 = mgr.getEngineByName("nashorn");

      // JavaScript code

        String script = "var greetings = 'Happy Programming!';";

        try {

            // create an object and call the function

            Object result1 = engine1.eval(script);

           // Print the output

            System.out.println(result1);

        } catch (ScriptException e) {

            e.printStackTrace();

        }

    }

}

  • Compile the program.
  • If the compilation is successful, run the program.

C:\raji\blog>javac NashornEg.java

C:\raji\blog>java NashornEg

Happy Programming!

Let us try some more scripting….

Java Script to display “Happy Birthday. Stay Blessed Always!!!!”.

Same program is used with java script code alone changed.

        String script = "var bMsg = 'Happy Birthday. Stay Blessed Always!!!!';";

Change the code. Execute the same program as below.

C:\raji\blog>javac NashornEg.java

C:\raji\blog>java NashornEg

Happy Birthday. Stay Blessed Always!!!!

That’s all. The java program to use JavaScript within the code is developed successfully.

Note: This JavaScript engine is used as standalone project on GitHub because it was deprecated in java11.

No comments:

Post a Comment