Groovy MOP,實現傳說中Java7.0的XML嵌入式文法

來源:互聯網
上載者:User
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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.