簡體   English   中英

如何從Java評估我自己的Groovy腳本?

[英]How can I evaluate my own Groovy script from Java?

我嘗試從Java類調用我自己的groovy腳本函數,用戶也可以使用標准表達式。

例如:

GroovyShell shell = new GroovyShell();
Script scrpt = shell.parse("C:/Users/Cagri/Desktop/MyCustomScript.groovy");

Binding binding = new Binding();
binding.setVariable("str1", "foo");
binding.setVariable("str2", "boo");             

scrpt.setBinding(binding);
System.out.println(scrpt.evaluate("customConcat(str1, str2)")); //my custom method
System.out.println(scrpt.evaluate("str1.concat(str2)"));

這是MyCustomScript.groovy

def area(def sf) {
    Feature f = new Feature(sf);
    f.getGeom().area;
}

def customConcat(def string1, def string2) {
    string1.concat(string2)
}

運行此行時scrpt.evaluate("str1.concat(str2)")按預期工作,但scrpt.evaluate("customConcat(str1, str2)")拋出異常:

groovy.lang.MissingMethodException: No signature of method: Script1.customConcat() is applicable for argument types: (java.lang.String, java.lang.String) values: [foo, boo]
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:78)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
at Script1.run(Script1.groovy:1)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:518)

我可以調用我的自定義方法,如下所示,它的工作原理

GroovyClassLoader loader = new GroovyClassLoader();
Class groovyClass = loader.parseClass(new File("C:/Users/Cagri/Desktop/IntergisGroovyScript.groovy"));

GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
Object res = groovyObject.invokeMethod("customConcat", new Object[]{"foo", "boo"});

但是,這次我找不到如何評估像substring,concat等標准表達式......

那么我該如何評估自定義和標准表達呢?

調用evaluate()來執行腳本方法不起作用,因為腳本中定義的方法不會以綁定結束。 但是,作為一種解決方法,您可以在綁定中存儲腳本(包含方法),然后使用該引用來執行其方法。 以下適用於我:

Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
Script scrpt = shell.parse(new File("src/test.groovy"));

binding.setVariable("str1", "foo");
binding.setVariable("str2", "boo");
binding.setVariable("tools", scrpt);

System.out.println(shell.evaluate("tools.customConcat(str1, str2)"));
System.out.println(shell.evaluate("str1.concat(str2)"));

或者,您可以使用Script.invokeMethod(name, args)直接調用腳本的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM