Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Dynamic Features and Metaprogramming

Expando and ExpandoMetaClass in Groovy

Build objects whose properties and methods are added on the fly with Expando, and extend real classes with ExpandoMetaClass, including constructors and statics.

Sometimes you need an object right now, without declaring a class for it: a fake collaborator for a test, a throwaway record, a plugin hook. Groovy gives you two tools for this. Expando is an empty object that grows properties and methods as you assign them. ExpandoMetaClass (the thing behind Class.metaClass.name = ...) does the same for classes that already exist.

Groovy is not available on this site, so the Groovy fences are read-only. The Java programs are labelled stand-ins that model the same behavior with maps.

Expando: a bag of properties and closures

GROOVY
def person = new Expando()
person.name = "Ada"
person.born = 1815
person.greet = { String other -> "Hi ${other}, I am ${name}" }

println person.name              // Ada
println person.greet("Charles")  // Hi Charles, I am Ada
println person.age               // null   (unknown properties are simply null)

Two facts make this work:

  1. Assigning a plain value stores a property.
  2. Assigning a closure stores a method. When the closure runs, name resolves against the expando, because the closure's delegate is the Expando itself.

You can also pass a map to the constructor to set initial properties:

GROOVY
def point = new Expando(x: 3, y: 4)
point.distance = { -> Math.sqrt(x * x + y * y) }
println point.distance()   // 5.0

Where Expando shines

Test doubles are the classic use. A service that is expected to have a send(msg) method can be replaced inline:

GROOVY
def sent = []
def fakeMailer = new Expando(send: { msg -> sent << msg })

notify(fakeMailer, "Build finished")
assert sent == ["Build finished"]

Groovy's duck typing means notify never checks the type. It only calls mailer.send(...).

If you need type safety, Expando is the wrong tool; use a real class, a trait, or a Spock mock (see Mocking and Stubbing in Spock). An expando cannot be passed where a Java interface is required without a coercion such as as Mailer on a map or closure.

ExpandoMetaClass on real classes

Every time you write SomeClass.metaClass.something = ..., Groovy upgrades the class's metaclass to an ExpandoMetaClass. You can add many kinds of members:

GROOVY
class Money {
  BigDecimal amount
  String currency
}

// instance method
Money.metaClass.plus = { Money other ->
  new Money(amount: delegate.amount + other.amount, currency: delegate.currency)
}

// property with a computed value
Money.metaClass.getCents = { -> (delegate.amount * 100).intValue() }

// static method
Money.metaClass.static.zero = { String cur -> new Money(amount: 0, currency: cur) }

// constructor
Money.metaClass.constructor = { String text ->
  def (a, c) = text.tokenize(" ")
  new Money(amount: a as BigDecimal, currency: c)
}

def total = new Money("5.50 EUR") + new Money("2.25 EUR")
println total.amount     // 7.75
println total.cents      // 775
println Money.zero("USD").amount   // 0

Notes:

  • Defining a method named plus makes the + operator work. See operator overloading for the full list of method names.
  • A getCents closure appears as the property cents, following the JavaBeans naming rule.
  • Overriding constructor this way is "append only": the original constructors still exist, and extra ones are added.

Adding several members at once

GROOVY
Money.metaClass {
  isZero = { -> delegate.amount == 0 }
  static {
    parse = { String s -> new Money(s) }
  }
}

The block form groups related changes and keeps the code readable.

Reaching the original method

If you replace an existing method but need the original, grab it before you override:

GROOVY
def original = String.metaClass.getMetaMethod("toUpperCase")
String.metaClass.toUpperCase = { -> "<<" + original.invoke(delegate) + ">>" }
println "abc".toUpperCase()   // <<ABC>>

Overriding methods of core classes like String is legal and almost always a bad idea. Add new names instead.

Inheritance and enabling the feature

Methods you add to a class are visible on its subclasses only if the subclass's metaclass is created after the change, or if you enable inheritance support:

GROOVY
ExpandoMetaClass.enableGlobally()

In current Groovy versions, ExpandoMetaClass is already used for most classes by default, and you rarely need to call this explicitly. Remember that every addition is global, so keep metaprogramming at the edges of the program and isolate it in well-named setup code (for example one bootstrap() method called from the application start).

Try it: an Expando as a map of closures (stand-in)

A Java Map<String, Object> can play the Expando: values are properties, functions are methods.

Java Stand-in: Expando built on a map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: a test double that records calls (stand-in)

This is the fake-mailer pattern from earlier, with the interface dropped in favor of a function slot.

Java Stand-in: recording fake mailer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does assigning a closure to an Expando property create?

    A closure stored in an Expando can be called like a method, and its delegate is the Expando.
  2. 2. What does new Expando().missing evaluate to?

    Unknown properties on an Expando are simply null.
  3. 3. How do you add a static method zero to a class Money at runtime?

    The static keyword in the metaClass chain registers a static method.
  4. 4. Which method name lets you use a + b on your own class through ExpandoMetaClass?

    Groovy maps the + operator to a method called plus.

Summary

  • Expando is an empty object whose properties and closure-methods you add by assignment.
  • It is ideal for quick test doubles and ad hoc data, and unknown properties read as null.
  • ExpandoMetaClass adds instance methods, computed properties, statics and constructors to existing classes.
  • Operator names such as plus become operators.
  • All class-level changes are global, so keep them in clearly named setup code.

Next: methodMissing and propertyMissing