Tuesday, 29 December 2015

Run Javascript from Java.

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 commons provides a project Jakarta Bean Scripting Framework (BSF) which gives implementation for a several set of scripting languages like Python, TCL, NetRexx including javascript and lot more.

here is code Example:

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