How to call Javascript function from Java

Sometime we are in need to call javascript function from Java to reuse the logic of javascript or for better maintainability we don’t want to duplicate that logic in Java. Following example show you how to call javascript function from java.

Following sample Javascript function (available in test.js file) we call from our Java application.

	function sayHello(name) {
		return "Hello " + name;
	}

Sample java code to call javascript function.

package com.elitejavacoder.javascript;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class CallJavascriptFromJava {

	public static void main(String[] args) {
		
		try {
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine javascriptEngine = manager.getEngineByExtension("js");
			
			// Get script from JS File
			FileInputStream fileInputStream = new FileInputStream("F:developmentjavascripttest.js");
			if (fileInputStream != null) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
		
				javascriptEngine.eval(reader);
				Invocable invocableEngine = (Invocable)javascriptEngine;
				
				// Invoke javascript function named "sayHello" with parameter "Atul"
				Object object = invocableEngine.invokeFunction("sayHello", new String[]{"Atul"});
				System.out.println("Result: " + object);
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

Above code will print “Result: Hello Atul”.