作为groovy类执行
作为groovy类执行:加载groovy类之后,通过反射的方式实例化,并调用指定的方法,返回结果。实例如下
private Object execGroovy(String groovyCode, String methodName, Object... params) {
try (GroovyClassLoader classLoader = new GroovyClassLoader()) {
Class groovyClass = classLoader.parseClass(groovyCode);
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
Method method = null;
try {
method = groovyClass.getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
LOGGER.warn("Groovy 脚本中不存在" + methodName + "方法");
}
if (method == null) {
method = groovyClass.getDeclaredMethods()[2];
}
return method.invoke(groovyObject, params);
} catch (InstantiationException | InvocationTargetException | IllegalAccessException | IOException e) {
LOGGER.error("Groovy 脚本执行出错,请检查脚本内容!", e);
return null;
}
}
切记使用try-with-resource或者在final方法中调用groovyClassLoader.close()
方法。
如果只是groovy脚本的方式编写的代码,没有类结构,也可以使用这种方式执行,因为groovy脚本都是隐式继承Script类的。
在linux系统上反射执行groovy还有未知问题…
作为groovy脚本方式执行
作为groovy脚本方式执行,使用以下java代码调用即可:
// 调用带参数的groovy shell时,使用bind绑定数据 Binding binding = new Binding(); binding.setProperty("name", "Juxinli"); GroovyShell groovyShell = new GroovyShell(binding); Object result = groovyShell.evaluate(new File("src/main/java/com/juxinli/groovy/GroovyShell_1_2.groovy")); logger.info(result.toString());
返回值为最后一句脚本的返回值,如果脚本没有返回值,则java中evaluate方法返回null;
核心执行方法是 groovyShell.evaluate 方法,它有许多重载的方法可以调用。
// GroovyShell_3_1.groovy
package com.juxinli.groovy.shell
def sayHello(String name) {
println "Привет, " + name
"GroovyShell_3_3中的sayHello()方法的返回值"
}
// 运行groovy方法
sayHello(name)
使用 GroovyScriptEngine 执行
GroovyScriptEngine从您指定的位置(文件系统,URL,数据库,等等)加载Groovy脚本,并且随着脚本变化而重新加载它们。
如同GroovyShell一样,GroovyScriptEngine也允许您传入参数值,并能返回脚本的值。
// GroovyScriptEngine的根路径,如果参数是字符串数组,说明有多个根路径
GroovyScriptEngine engine = new GroovyScriptEngine("src/main/java/com/juxinli/groovy/shell/");
//GroovyScriptEngine engine = new GroovyScriptEngine(new String[] {"src/main/java/com/juxinli/groovy/shell/"});
Binding binding = new Binding();
binding.setVariable("name", "juxinli");
Object result1 = engine.run("GroovyShell_3_1.groovy", binding);
System.out.println(result1);