2014-01-13 51 views
2

我在用python,groovy和javascript编写的不同脚本文件上有相同的自定义函数。用户可以选择一个想要使用的脚本。我想以通用的方式从这些脚本中调用函数。使用ScriptEngine从Java调用自定义脚本函数

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")); 

有了这样我可以打电话给我的职务甚至改变ScriptEngineManager参数为“JavaScript的”或“常规”以更改与“CustomJs.js”或“Customgroovy.groovy”读者文件。

不过,我不知道那有没有办法来调用功能,而无需使用invokeFunction象下面这样:

首先,评估脚本,并把结果放到这个对象绑定,然后调用函数。

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); 

所以,这是对我来说最普通的方式,如果有这样的方式或有任何其他的建议吗?

回答

0

下面的方法可能是有帮助避免呼叫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"); 

} 

附接(在/data-encoder-dir/testFunc.groovy)一个常规的文件:

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

testFunc(x) 

PS:I”使用groovyjavascript脚本或其他java脚本引擎兼容将遵循相同的路线。