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> -->

你可能感兴趣的:(xml,嵌入式,Ruby,groovy,java7)