2014-01-13 71 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腳本引擎兼容將遵循相同的路線。