2017  Kodetalk | Feedback | Privacy Policy | Terms | About

How to execute a Javascript function using Java and print the return result from Javascript function

I want to know like how to execute a Javascript function using Java code as i know there are API's by using, we can execute a Javascript. Now i wanted to know a complete example for executing a Javascript function and getting the return result as object and print the data using java sop.


Hope this will help you:

package com.js;

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

 * @author debs 02 January 2017
public class ExecuteScript {

	public static void main(String[] args) throws ScriptException, NoSuchMethodException {
		ScriptEngineManager factory = new ScriptEngineManager();
		ScriptEngine engine = factory.getEngineByName("JavaScript");
		engine.eval("function add(a, b){return (a+b);}");
		Invocable invocable = (Invocable) engine;
		Object obj = invocable.invokeFunction("add", 2, 3);
		System.out.println("Return result : " + obj);
Answer is