Groovy是一个运行于jvm上的语言,所以理所当然能够与java协同工作,下面列出原生集成groovy与java的几种方式
1、基于Shell脚本
Binding binding = new Binding();
binding.setVariable("foo", new Integer(2));
GroovyShell shell = new GroovyShell(binding);
//执行groovy脚本
Object value = shell.evaluate("println 'Hello World!'; x = 123; return foo * 10");
//也可以执行groovy脚本文件,如果TestGroovy.groovy是定义的一个类对象,默认会去执行main函数
//Object obj = shell.evaluate(new File("src/TestGroovy.groovy"));
assert value.equals(new Integer(20));
assert binding.getVariable("x").equals(new Integer(123));
2、基于通用的基础类
Binding binding = new Binding();
CompilerConfiguration config = new CompilerConfiguration();
config.setScriptBaseClass("MyScript");//MyScript.groovy文件默认在src目录下
GroovyShell shell = new GroovyShell(ScriptBaseTest.class.getClassLoader(), binding, config);
Object rst = shell.evaluate("test1('d')");//执行MyScript.groovy脚本的test1方法(非私有)
System.out.println(rst);//输出返回的对象
3、基于groovy的类加载器
ClassLoader loader = GroovyClassLoaderTest.class.getClassLoader();
//通过java类加载器构建一个groovyclass加载器
GroovyClassLoader groovyClassLoader = new GroovyClassLoader(loader);
//动态解析加载指定的groovy脚本文件
Class groovyClz = groovyClassLoader.parseClass(new File("src/GroovyClassLoaderTest2.groovy"));
//构建一个groovyobject实例
GroovyObject groovyObject = (GroovyObject) groovyClz.newInstance();
groovyObject.setProperty("name", "捷克");
System.out.println(groovyObject.getProperty("name"));
groovyObject.invokeMethod("test1", "哈哈");
Object obj = groovyObject.invokeMethod("test2", null);//动态执行test2方法(私有也行)
System.out.println(obj);
Binding对象:
Bindind对象可以绑定参数对象传递到执行的脚步中使用
例如基于shell的执行方式,可以在脚本中直接使用foo参数
GroovyScriptEngine对象:
通过GroovyScriptEngine在初始化指定的目录或url路径下执行脚本
String[] roots = new String[] { "/my/groovy/script/path" };
//通过指定的roots来初始化GroovyScriptEngine
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
Binding binding = new Binding();
binding.setVariable("input", "world");
//在初始化指定的roots下查找hello.groovy并执行
gse.run("hello.groovy", binding);
System.out.println(binding.getVariable("output"));
hello.groovy文件:
output = "Hello, ${input}!"