简体   繁体   中英

Calling custom script function with ScriptEngine from Java

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 :

@Test
public void test60_ScriptEngineTest()
        throws URISyntaxException, ScriptException, NoSuchMethodException, FileNotFoundException {

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("groovy");
    Compilable compilable = (Compilable) engine;
    Bindings bindings = engine.createBindings();

    URL url=getClass().getResource("/data-encoder-dir/testFunc.groovy");
    File script =new File(url.toURI());
    Reader reader = new FileReader(script);
    CompiledScript compiledScript = compilable.compile(reader);

    bindings.put("x", 5011);
    String result = (String) compiledScript.eval(bindings);
    assertEquals(result, "5011");

}

a groovy file attached (in /data-encoder-dir/testFunc.groovy):

public String testFunc(Integer bd) {
    return bd.toString();
}

testFunc(x)

PS: I'm using groovy , the javascript scenario or other java script engine compatible would follow the same route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM