Sunday 3 February 2013


Run Javascript from Java:

Scripts can be executed from within java in the JVM. Let us take javascript language for this example. There are couple of important classes in this package and they are:-

ScriptEngineManager:


This does two key functions, discovery of script engine and storing data in context and allowing it to be shared with programs. The key/value data stored is available for all script engines and should be considered as global data.

ScriptEngine:

This is an interface available part of java api. This should be implemented separately for every scripting languages. For javascript in the Oracle JDK (from 1.6) by default an implementation is available. Apache commonsprovides a project Jakarta Bean Scripting Framework (BSF) which gives implementationfor a several set of scripting languages like Python, TCL, NetRexx including javascript and lot more.

Example to Run Javascript in Java:

import javax.script.*;
public class JavaJavaScript {
public static void main(String args[]) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName( "javascript" );
engine.eval( "var x = 10;" );
engine.eval( "var y = 20;" );
engine.eval( "var z = x y;" );
engine.eval( "print (z);" );
}
}

No comments:

Post a Comment