动态Groovy

这一部分将向您展示如何使用Groovy的动态特性,比如实现GroovyObject接口和使用ExpandoMetaClass(可扩展元类)——一个允许你添加方法、属性和构造器的可扩展的元类。

动态方法调用

就算你直到使用方法时才知道方法名,你也可以调用这个方法:

class Dog {
  def bark() { println "woof!" }
  def sit() { println "(sitting)" }
  def jump() { println "boing!" }
}
 
def doAction( animal, action ) {
  animal."$action"()                  // 引入方法中传入了action名
}
 
def rex = new Dog()
 
doAction( rex, "bark" )               // 打印“woof!”
doAction( rex, "jump" )               // 打印“boing!”

当你有一个参数列表时,你也可以“展开”方法调用的参数:

def max(int i1, int i2) {
    Math.max(i1, i2)
}
def numbers = [1, 2]
assert max( *numbers ) == 2

而且,这在使用GString进行引用绑定时依然有效:

someObject."$methodName"(*args)
 
wiki/user_guide/dynamic_groovy.txt · 最后更改: 2008-09-14 09:37 由 johnny
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki