This post is to describe how to call a java script from java code.
Below is java file.In which there is a main method.In this main method a script engine instance is taken.This script engine is already with jdk.For this one need not to add any other jar file.
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineManager;
- import javax.script.ScriptException;
- public class Driver {
- /**
- * @param args
- * @throws FileNotFoundException
- */
- public static void main(String[] args) throws FileNotFoundException {
- try {
- /**
- * To call a anonymous function from java script file
- */
- ScriptEngine engine = new ScriptEngineManager()
- .getEngineByName("javascript");
- FileReader fr = new FileReader("src/js/MySpec.js");
- engine.eval(fr);
- } catch (ScriptException scrEx) {
- scrEx.printStackTrace();
- }
- }
- }
Below is the java script file with an anonymous fuction.This function is to print on the console.
- // java script anonumous function
- (function() {
- print('Hello world');
- })();
Below is the folder structure of the project.
Your Suggestions Are Always Welcomed.