Create demo2.js file
var fn1 = function(fullName) {
print('Hello ' + fullName);
}
var fn2 = function(a, b) {
print('Sum: ' + (a + b));
}
Invoking Javascript Functions from Java With Parameters
package pmk.learnjava8withrealapps.nashorn;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Demo2 {
public static void main(String[] args) {
try {
ScriptEngine se = new ScriptEngineManager()
.getEngineByName("nashorn");
se.eval(new FileReader("src\\pmk\\learnjava8withrealapps\\nashorn\\demo2.js"));
Invocable i1 = (Invocable)se;
i1.invokeFunction("fn1", "Kevin");
Invocable i2 = (Invocable)se;
i2.invokeFunction("fn2", 1, 2);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Output
Hello Kevin
Sum: 3