I have same custom functions with the same names on different script files written in python, groovy and javascript. User can choose one of the scripts that want to use. I want to call functions from these scripts in generic way.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("python");
Bindings bindings = engine.createBindings();
engine.eval(new FileReader("C:/Users/Cgr/Desktop/CustomPython.py");
Invocable inv = (Invocable) engine;
System.out.println(inv.invokeFunction("customConcatFunc", "str1", "str2"));
With this way I can call my functions even change ScriptEngineManager parameter as "javascript" or "groovy" with changing reader files with "CustomJs.js" or "Customgroovy.groovy".
However, I wonder that is there a way to call functions without using invokeFunction
like below:
First, evaluate script and put the result on binding then calling function on this object.
bindings.put("x", "str1");
bindings.put("y", "str2");
bindings.put("script", engine.eval(new FileReader("C:/Users/Cgr/Desktop/CustomgrPython.py")));
engine.eval("script.customConcatFunc(x,y)", bindings);
So, this is the most generic way for me if there is way like this or are there any other suggestions?
The method below might be helpful avoiding call
invokeFunction
:a groovy file attached (in /data-encoder-dir/testFunc.groovy):
PS: I'm using
groovy
, thejavascript
scenario or other java script engine compatible would follow the same route.