上一篇:Java动态调用Groove代码(1)-GroovyClassLoader
FunGroove.groovy
package com.chy.groovy
void print(){
System.out.println("没有参数!!!!");
}
//执行方法
print();
FunArgGroove.groovy
package com.chy.groovy
String printArg(String name){
System.out.println("参数:"+name);
return "返回结果:"+name;
}
//执行方法
printArg(arg);
java
package com.chy;
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
import java.io.IOException;
/**
* @Title: GroovyScriptEngineApp
* @Description: 演示 GroovyScriptEngine 方式
* @author chy
* @date 2018/9/13 0:06
*/
public class GroovyScriptEngineApp {
public static void main(String[] args) {
try {
// GroovyScriptEngine的根路径,如果参数是字符串数组,说明有多个根路径
GroovyScriptEngine engine = new GroovyScriptEngine("src/main/java/com/chy/groovy/");
Binding binding1 = new Binding();
Object result1 = engine.run("FunGroove.groovy", binding1);
if(null!=result1) {
System.out.println(result1);
}
System.out.println("===================================");
Binding binding2 = new Binding();
// arg 和 参数同名
binding2.setVariable("arg", "测试参数");
Object result2 = engine.run("FunArgGroove.groovy", binding2);
System.out.println(result2);
} catch (IOException e) {
e.printStackTrace();
} catch (ResourceException e) {
e.printStackTrace();
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
未完待续.......................