Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.