在Java中执行 Groovy Script 方法

如何在Java中执行 Groovy Script,例如:

GroovyShell shell = new GroovyShell();
Script scrpt = shell.parse("script.groovy");

Binding binding = new Binding();
binding.setVariable("str1", "value1");
binding.setVariable("str2", "value2");           

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


script.groovy:

def customConcat(def str1, def str2) {
str1.concat(str2)
}

正常执行System.out.println(scrpt.evaluate("str1.concat(str2)"));
执行System.out.println(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: [value1, value2]
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来加载却可以执行:

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[]{"value1", "value2"});

这种调用evaluate()执行脚本方法行不通是因没有脚本里定义的方法没有绑定,因此可以把script绑定给binding,然后执行的binding的引用方法:

Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
Script scrpt = shell.parse("script.groovy");

binding.setVariable("str1", "value1");
binding.setVariable("str2", "value2");
binding.setVariable("newConcat", scrpt);

System.out.println(scrpt.evaluate("newConcat.customConcat(str1, str2)"));
System.out.println(scrpt.evaluate("str1.concat(str2)"));

或者使用:

System.out.println(scrpt.invokeMethod("customConcat", new String[]{"value1","value2"}));

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/8ecf833ae50f70b89ba5c37dccb70685.html