加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy全攻略--嵌入篇

发布时间:2020-12-14 16:51:28 所属栏目:大数据 来源:网络整理
导读:Groovy被设计得非常轻量级,很容易迁入到任何Java应用系统。 你可以使用BSF将Groovy脚本嵌入任何Java代码中.但是Groovy提供了一个轻量级的紧密集成.下面是3种主要方法: 1.使用Shell调试脚本或表达式 在Groovy中你可以使用GroovyShell对Groovy脚本和表达式进行
Groovy被设计得非常轻量级,很容易迁入到任何Java应用系统。
你可以使用BSF将Groovy脚本嵌入任何Java代码中.但是Groovy提供了一个轻量级的紧密集成.下面是3种主要方法:

1.使用Shell调试脚本或表达式
在Groovy中你可以使用GroovyShell对Groovy脚本和表达式进行调试.GroovyShell允许你通过Binding对象传入或传出变量.

// ?从Java代码中调用Groovy语句

Binding?binding?=? new?Binding();

binding.setVariable("foo",? new?Integer(2));

GroovyShell?shell?=? new?GroovyShell(binding);


Object?value?=?shell.evaluate("println?'Hello?World!';?x?=?123;?return?foo?*?10");

assert?value.equals( new?Integer(20));

assert?binding.getVariable("x").equals( new?Integer(123));

2.在Java中动态调用运行Groovy代码
你可以使用GroovyClassLoader将Groovy的类动态地载入到Java程序中并直接使用或运行它.
下面是一个例子:

ClassLoader?parent?=?getClass().getClassLoader();

GroovyClassLoader?loader?=? new?GroovyClassLoader(parent);

Class?groovyClass?=?loader.parseClass( new?File("src/test/groovy/script/HelloWorld.groovy"));


// ?调用实例中的某个方法

GroovyObject?groovyObject?=?(GroovyObject)?groovyClass.newInstance();
? ?Object[]?args?=? {};

groovyObject.invokeMethod("run",?args);

如果你想使用一个用Groovy脚本实现的接口,你可以这么使用它:

GroovyClassLoader?gcl?=? new?GroovyClassLoader();

Class?clazz?=?gcl.parseClass(myStringwithGroovyClassSource?"SomeName.groovy");

Object?aScript?=?clazz.newInstance();

MyInterface?myObject?=?(MyInterface)?aScript;

myObject.interfaceMethod();

??


如果某个Groovy类实现口MyInterface接口,那么上面的代码就会很好的工作.myObject的使用方法与其他实现了MyInterface接口的Java对象一样.

3.Groovy脚本引擎
对于那些想将Groovy脚本嵌入到服务器并且在每次修改后重新装入的人来说,Groovy脚本引擎提供了一个彻底的解决方案.你可以设定系列CLASSPATH作为根来初始化Groovy脚本引擎,这些GLASSPATH可以是URL也可以是目录名.接着你就可以这些根路径下的任何Groovy脚本了.GSE会跟踪脚本间的依赖关系,因此如果任何有依赖关系的脚本被修改,整颗树将会重新编译和载入.
另外,每次执行脚本时,你都可以传入一个包含脚本可接受属性的Binding.脚本执行完以后,传入脚本中的那些属性在Binding中依然有效.下面是一个例子:
/my/groovy/script/path/hello.groovy:

output?=?"Hello,?${input}!"

import ?groovy.lang.Binding;

import ?groovy.util.GroovyScriptEngine;


? String[]?roots? = ? new ?String[]? {? " /my/groovy/script/path " ?};

GroovyScriptEngine?gse? = ? new ?GroovyScriptEngine(roots);

Binding?binding? = ? new ?Binding();

binding.setVariable( " input ",? " world " );

gse.run( " test.groovy ",?binding);

System.out.println(binding.getVariable( " output " ));
将打印 "Hello,world!". 4.运行时依赖 和JDK1.4一样,Groovy Jar也依赖与ASM库上的运行时,ASM库包括4个Jar(asm-2.1.jar,asm-util-2.1.jar,asm-attrs-2.1.jar and asm-analysis-2.1). 也就是说,只要将上面的5个Jar添加到路径中,你就能将轻松地Groovy嵌入到你的应用里. 另一种方案可以不用那么多的Jar.你可以用GROOVY_HOME/embeddable目录下的groovy-all-1.0-beta-x.jar.这个Jar包将Groovy和ASM组合打包成一个方便的Jar包.注意:groovy-all-1.0-beta-x.jar中的ASM类使用了不同的命名空间,因此要避免与使用ASM的库发生冲突. ?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读