Let's say have file like this
(function () {
function change() {
print('test');
}
function test() {
return 'Testing';
}
})();
How to pass argument to this function using nashorn? I don't want run it via terminal, I have to create method that takes String as argument and process it with js code.
Your script above defines an anonymous function and calls it immediately! If you 'eval' that you'll get the result of that function. If you want to define an anonymous function and call it from java code, you can write something like this:
import javax.script.*;
import jdk.nashorn.api.scripting.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
// define an anoymous function
JSObject multiply = (JSObject) e.eval("function(x, y) { return x*y; }");
// call that anon function
System.out.println(multiply.call(null, 34, 5));
// define another anon function
JSObject greet = (JSObject) e.eval("function(n) { print('Hello ' + n)}");
greet.call(null, "nashorn");
}
}