This section details how to go about using the dynamic features of Groovy such as implementing the GroovyObject interface and using ExpandoMetaClass, an expandable MetaClass that allows adding of methods, properties and constructors.

この章ではGroovyの GroovyObject インタフェースを実装したり、 ExpandoMetaClass を使ったり、メソッドやプロパティやコンストラクタを追加できる拡張可能なメタクラスなどのような動的機能をどうやって使うのかを詳述します。

Compile-time metaprogramming is also available using Compile-time Metaprogramming - AST Transformations

コンパイル時のメタプログラミングはJapanese Compile-time Metaprogramming - AST Transformationsを利用しても可能です。

Dynamic Method Invocation


You can invoke a method even if you don't know the method name until it is invoked:


class Dog {
  def bark() { println "woof!" }
  def sit() { println "(sitting)" }
  def jump() { println "boing!" }

def doAction( animal, action ) {
  animal."$action"()                  //action name is passed at invocation

def rex = new Dog()

doAction( rex, "bark" )               //prints 'woof!'
doAction( rex, "jump" )               //prints 'boing!'

You can also "spread" the arguments in a method call, when you have a list of arguments:


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

This also works in combination of the invocation with a GString: