Groovy MOP实现mini-language 如传说中Java7.0的XML嵌入式语法

作者:江南白衣

Groovy的Team Leader-- Guillaume Laforge说,MOP(Meta Object Protocol)是他最喜欢的Groovy特性。

MOP是对属性、方法进行拦截解释的简单机制,intercept 已经因为AOP而被大家熟悉。
Groovy的类都继承于GroovyObject,GroovyObject有get/setProperty()和invokeMethod()两个函数,当客户调用不存在的属性和方法时,就会交由这两个函数来处理,在Ruby里,这个方法被更贴切的命名为method_missing()。Groovy类可以通过重载这两个函数,加入自己的hook和behavior,比Java简单的多的实现ProxyDelegator。

而更重要的是,MOP函数可以充当领域语言解释者的角色,拦截一些存在于领域语言的而在Class里根本没有定义的属性、方法来进行解释,这就是Groovy里XML嵌入式语法的魔法根源
IBM DW有一篇专门的文章 :《PRACTICALLY mini-languages and MOPs Of Groovy:》
比如如下的xml

< shop >
< book name ="foo" >
< writer > 庄表伟 writer>
book>
shop>

可以用groovy这样访问

printlnnode.book.writer.text()

node类当然没有book,writer这样属于领域语言的属性,但通过重载getPropety(String name)函数,node类可以把对book,writer属性的访问,转换成相应DOM节点的访问。
实现请参看org.codehaus.groovy.sandbox.util.XMLList类的public Object getProperty(final String elementName)函数。

Guillaume Laforge说,It's an aspect of Groovy which makes the language very powerful, but rare are those who really know and use it.<!-- --><!-- <BR> <p> <I>Brian Sletten is a liberal arts-educated software engineer with a focus on forward-leaning technologies. He grew up around the world in the Philippines, Germany and Japan. He has a background as a system architect, a developer, a mentor and a trainer. His experience has spanned defense, finance and commercial domains with communication software, secure software consulting, 3D simulation/visualization systems, Grid Computing and a Semantic Web-based document processing pipeline. Brian speaks regularly with the NoFluffJustStuff conference on aspect-oriented programming, design patterns, software metrics, .NET/Java integration and ZeroConf-based networking protocols. He has also spoken at JavaOne twice and at user groups around the country. He lives in Fairfax, VA, where he runs his software consulting business, Bosatsu Consulting, Inc. He is a happy Apple PowerBook user who thinks "Once you go Mac, you never go back."</i> </p> -->

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值