iT邦幫忙

1

Groovy重要觀念(1)-MOP中methodMissing及propertyMissing

一般Script型語言,如果我理解對的話,即便變數打錯或是方法打錯,最多是跑不出結果或是跑出來不知道是什麼東西,Groovy MOP中可以撰寫methodMissing以及propertyMissing方法決定run time時找不到方法或是變數時的預設行為。
就誠如上述,methodMissing的General form為

Object methodMissing(String name, Object arguments)

而propertyMissing的General form為

Object propertyMissing(String name)

接下來就直接舉例吧!

class FDDR{
    String no
    int rev
    String title
    
    def methodMissing(String name, Object args){ //method不存在時,預設執行的方法
        println "You are calling the method: $name which does not exist."
    }
    //用Closure來定義做什麼事,run-time可以比較有彈性
    Closure dosomething={name ->  println "You are accessing the property: $name which does not exist."} //第一種回應方式
    def propertyMissing(String name){ //property不存在時,預設執行的方法
       dosomething(name) 
    }

}
def src1=new FDDR()
src1.doPost()
src1.FDI  //第一次存取不存在的property
src1.dosomething={name-> println 'Please delcare the property before using it.'} //改寫closure,可重新定義預設回應
src1.FPR  //改寫closure後,再呼叫不存在的property時,回應就改變了

執行結果:

You are calling the method: doPost which does not exist.
You are accessing the property: FDI which does not exist.
Please delcare the property before using it.

如果能靈活運用closure,那程式功力可以更上一層樓,應可減少不少程式碼,但觀念要很清楚就試了,自己正努力鑽研中,與IT人共勉之。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言