加入收藏 | 设为首页 | 会员中心 | 我要投稿 江门站长网 (https://www.0750zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

在Java中执行 Groovy Script 技巧

发布时间:2021-11-20 17:42:03 所属栏目:教程 来源:互联网
导读:如何在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.setBindin

如何在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"}));

(编辑:江门站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读