3

我尝试从 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 等......

那么我应该如何评估自定义和标准表达式呢?

4

1 回答 1

8

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

Alternatively you could invoke methods of the script directly using Script.invokeMethod(name, args).

于 2014-01-03T16:16:28.563 回答