Groovy and Grails Recipes翻译之旅——面向对象的Groovy(15)

 

4.15.   如何拦截对象的所有方法调用?

清单4.34演示如何通过重载GroovyObject接口的invokeMethodgetPropertysetProperty的方法,实现对Groovy类的方法和属性访问的拦截。该例子也演示了如何给一个类增加一个动态查询器方法,如findAllStartsWithX,该方法将返回列表中以X开头的所有元素。例如,当传入列表["Groovy","is","Great", "isn't"],调用findAllStartsWithG方法将返回["Groovy","Great"],而调用findAllStartsWithi则返回["is","isn't"],等等。

 

class MOP {

    def list

    def getProperty(String name) { println "The list is $list" }

    def invokeMethod(String name, args){

        if (name.startsWith("findAllStartsWith")){

             String startsWith = name[-1]

             return list.findAll{it.startsWith(startsWith)}

        }

 

    }

}

def mop = new MOP(list:["Groovy","is","Great", "isn't"])

assert mop.findAllStartsWithG() == ["Groovy","Great"]

assert mop.findAllStartsWithi() == ["is","isn't"]

assert mop.findAllStartsWithZ() == []

println mop.list //Prints: The list is ["Groovy", "is", "Great", "isn't"]

你可能感兴趣的:(grails,groovy)