歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

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

Copyright © Linux教程網 All Rights Reserved