My Thoughts: Running JavaScript in the Java platform

Tuesday, October 11

Running JavaScript in the Java platform


Java is one of the powerful language.And we can do so mang things with it .

If you want to integrate javascript code with your javacode then it is very simple.
the steps are
1. Create ScriptEngineManager object
2.Get the ScriptEngine object from scriptEngineManager
3.Evaluate a script using the ScriptEngine object.

Here is the sample code :
You need to include "javax.script" package.

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.*;

public class Javascript {


public static void main(String[] args) {
// Creating ScriptEngineManager
ScriptEngineManager mgr = new ScriptEngineManager();
//getting the ScriptEngine object
 ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
 try {
//Evaluate the script.For this we are using eval method
   jsEngine.eval("print('Hello, world!')");
 

 } catch (ScriptException ex) {
     ex.printStackTrace();
 }  

 try {
//We can import even java pacjages from script
   jsEngine.eval("importPackage(javax.swing);" +
       "var optionPane = " +
       "  JOptionPane.showMessageDialog(null, 'Hello, world!');");
 } catch (ScriptException ex) {
   ex.printStackTrace();
 }

}

}

No comments:

Post a Comment