Execute Javascript Function in Java>
In this example, We will show you simple program about, How to Execute Javascript function in Java. The example program has been tested and shared in the same post.
Example Program
package com.dineshkrish; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** * * @author Dinesh Krishnan * */ public class JavaScriptRunner { public static void main(String[] args) { // script engine final String ENGINE_NAME = "nashorn"; // defining Script Engine Manager object ScriptEngineManager manager = new ScriptEngineManager(); // defining the Script Engine ScriptEngine engine = manager.getEngineByName(ENGINE_NAME); try { // file name or complete file name with path final String fileName = "script.js"; // creating the file object by passing the file name as argument File file = new File(fileName); // creating the file reader object by passing file object as argument FileReader fileReader = new FileReader(file); // loading the reader object to engine engine.eval(fileReader); // creating invocable object Invocable invocable = (Invocable)engine; // invoking the function 'sayHello('Dinesh Krishnan')' String message = (String)invocable.invokeFunction("sayHello", "Dinesh Krishnan"); // printing the result System.out.println(message); // invoking the function 'sayBye('Dinesh Krishnan')' message = (String)invocable.invokeFunction("sayBye", "Dinesh Krishnan"); // printing the result System.out.println(message); } catch (ScriptException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (NoSuchMethodException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
Sample Script (script.js)
var sayHello = function(name) { return "Hello, "+name; }; var sayBye = function(name) { return "Bye, "+name; };
Output
Hello, Dinesh Krishnan Bye, Dinesh Krishnan
References
1. JavaDoc – ScriptEngineManager Class
2. JavaDoc – ScriptEngine Interface
3. JavaDoc – File Class
4. JavaDoc – FileReader Class
5. JavaDoc – Invocable Interface
6. JavaDoc – invokeFunction() method
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet