我尝试从 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"});
但是,这次我找不到如何评估标准表达式,如子字符串、concat 等......
那么我应该如何评估自定义和标准表达式呢?