Groovy之嵌入java协同工作

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}!"

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值