Running JavaScript code on Java platform

14 April, 2014
We can integrate JavaScript code within the Java code. Its pretty simple and straight forward. Follow the below steps to run Javascript code within the Java code.

1. Create an instance of ScriptEngineManager object
2. Get the ScriptEngine object from ScriptEngineManager
3. Run the JavaScript code using the ScriptEngine object.

Sample code:
The scripting API consists of interfaces and classes that define Java Scripting Engines and provides a framework for their use in Java applications.


import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavaScriptDemo {
  public static void main(String[] args) {
  
   // Create instance of ScriptEngineManager
   ScriptEngineManager scriptEngineMgr = new ScriptEngineManager();
   
   //Get the ScriptEngine object
   ScriptEngine jsEngine = scriptEngineMgr.getEngineByName("JavaScript");
    try {
     //Run the JavaScript code using eval method
        jsEngine.eval("print('Hello, world!')");
     } catch (ScriptException ex) {
          ex.printStackTrace();
     }   
     
     try {
      //Import java packages from script
         jsEngine.eval("importPackage(javax.swing);" + "var optionPane = " + "  JOptionPane.showMessageDialog(null, 'Hello, world!');");
       } catch (ScriptException ex) {
         ex.printStackTrace();
       }
  }
}

Below is the screenshot of the output when the above code is run on Eclipse.




No comments:

Post a Comment