Groovy的Team Leader-- Guillaume Laforge说,MOP(Meta Object Protocol)是他最喜欢的Groovy特性。
使用MOP可以简单的对属性和方法进行拦截和解释,intercept 已经因为AOP而被大家熟悉。在Groovy里,通过重载GroovyObject的get/setProperty()函数和invokeMethod()函数,可以加入自己的hook和behavior,比Java简单的多的实现proxy和delegator。
而更重要的是,MOP函数可以充当领域语言解释者的角色,拦截一些在Class里根本没有定义的属性、方法来进行解释,这就是Groovy里XML嵌入式语法的魔法根源。
比如如下的xml
<shop><book name="foo"><writer>庄表伟</writer></book></shop>
可以用groovy这样访问
println node.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.
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."
--