What's an elegant way to have a reusable metaclass code in Groovy?

227 views Asked by At

I would like to apply a meta-programming transformation to some of my classes, let's say by adding printXxx methods, like this:

class Person {
  String name
}

def p = new Person()
p.printName() // does something

I have a rough idea how this can be done once I have a metaclass:

Person.metaClass.methodMissing = { name, args ->
  delegate.metaClass."$name" = { println delegate."${getPropName(name)}" }
  delegate."$name"(*args)
}

Now how do I turn this code into a reusable "library"? I would like to do something like:

@HasMagicPrinterMethod
class Person {
  String name
}

or

class Person {
  String name

  static {
    addMagicPrinters()
  }
}
2

There are 2 answers

0
Will On

You can go for a mixin approach:

class AutoPrint {
    static def methodMissing(obj, String method, args) {
        if (method.startsWith("print")) {
            def property = (method - "print").with { 
                it[0].toLowerCase() + it[1..-1] 
            }
            "${obj.getClass().simpleName} ${obj[property]}"
        }
        else {
            throw new NoSuchMethodException()
        }
    }
}

You can mix it with a static block:

class Person {
    static { Person.metaClass.mixin AutoPrint }
    String name
}

def p = new Person(name: "john doe")


try {
    p.captain()
    assert false, "should've failed"
} catch (e) {
    assert true
}

assert p.printName() == "Person john doe"

Or with expandoMetaClass:

class Car {
    String model
}

Car.metaClass.mixin AutoPrint

assert new Car(model: "GT").printModel() == "Car GT"

Because 7 months later is the new 'now' :-)

1
Dónal On

Define the behaviour you want to add as a trait

trait MagicPrinter {                           
  void printProperties() {  
    this.properties.each { key, val ->
      println "$key = $val"
    }
  }          
}

Then add this trait to a class

class Person implements MagicPrinter {
  String name
}

Now use it!

new Person(name: 'bob').printProperties()