Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Dynamic Features and Metaprogramming

The MetaClass and Dynamic Dispatch in Groovy

See how Groovy decides which method to run: the MetaClass registry, runtime dispatch, respondsTo, hasProperty, and adding methods to existing classes.

In Java the compiler decides which method a call goes to. In Groovy the decision is made at runtime, every time the call runs. Behind every Groovy object sits a MetaClass, a registry that knows the object's methods, properties and constructors, and that you are allowed to change while the program runs. That is the foundation of everything in this chapter: categories, Expando, methodMissing, builders and most DSLs.

Groovy cannot be run on this site. The Groovy code below is read-only. The runnable examples are small Java stand-ins that model the same idea (a table of methods consulted at runtime), so you can watch the mechanism work. Each one is labelled as a stand-in.

What happens when you call a method

Take this Groovy line:

GROOVY
def text = "groovy"
println text.toUpperCase()

The static type of text is def, so the compiler cannot bind toUpperCase to anything. Instead it emits a call site, and at runtime Groovy asks the metaclass of String for a method named toUpperCase that accepts no arguments. If one exists it is invoked. If not, Groovy tries methodMissing, then invokeMethod, and finally throws MissingMethodException.

flowchart TD
  A["obj.name(args)"] --> B["Find MetaClass of obj"]
  B --> C{"Method in metaclass?"}
  C -- yes --> D["Invoke it"]
  C -- no --> E{"methodMissing defined?"}
  E -- yes --> F["Call methodMissing"]
  E -- no --> G["Throw MissingMethodException"]

Dispatch is looked up on the runtime type of the receiver, and also on the runtime types of the arguments.

That second point matters. Groovy uses multiple dispatch: overloads are chosen by the actual runtime types of the arguments, not by the declared types.

GROOVY
String describe(Object o)  { "object" }
String describe(String s)  { "string" }

Object x = "hello"
println describe(x)   // string  (Java would print "object")

Java picks describe(Object) because x is declared Object. Groovy looks at the real value and picks describe(String).

Inspecting a metaclass

You can ask any object what it can do:

GROOVY
def s = "abc"
println s.metaClass.respondsTo(s, "toUpperCase")   // a non-empty list, so true in a condition
println s.metaClass.hasProperty(s, "bytes") != null
println s.metaClass.methods*.name.unique().size() > 50
  • respondsTo(obj, name) returns the list of matching MetaMethod objects. An empty list is falsy, so if (obj.respondsTo("quack")) is a common duck-typing guard.
  • respondsTo(obj, name, argTypes) also checks parameter types.
  • hasProperty(obj, name) returns a MetaProperty or null.
  • metaClass.methods and metaClass.properties list everything, including methods Groovy adds through the Groovy Development Kit (GDK), such as String.reverse().

Adding a method to an existing class

Because the metaclass is mutable, you can give an existing class new behavior. Assigning a closure to metaClass.name adds a method:

GROOVY
String.metaClass.shout = { -> delegate.toUpperCase() + "!" }

println "hello".shout()    // HELLO!

Inside the closure, delegate is the object the method is called on (you will study closures in detail in Closures in Depth). Arguments work the same way:

GROOVY
Integer.metaClass.times2 = { -> delegate * 2 }
Integer.metaClass.plusN = { int n -> delegate + n }

println 21.times2()   // 42
println 5.plusN(10)   // 15

Adding properties and static methods uses the same registry:

GROOVY
String.metaClass.static.fromCsv = { String csv -> csv.split(",").toList() }
println String.fromCsv("a,b,c")   // [a, b, c]

Changes made through metaClass are global for the whole JVM process (for ExpandoMetaClass on a class). Another library in the same process sees your new method too, and tests can leak behavior into one another. Prefer categories for limited scope, and reset a metaclass in test cleanup.

Per-instance metaclasses

You can also change a single object, leaving the class untouched:

GROOVY
def a = new Date()
def b = new Date()
a.metaClass.label = { -> "special date" }

println a.label()                 // special date
println b.respondsTo("label")     // false  (empty list)

Per-instance changes are cheap to reason about, but they make each such object carry its own metaclass, which is slower.

Dynamic versus static: @CompileStatic

Dynamic dispatch has a cost and removes compile-time checking. Groovy lets you opt out per class or method:

GROOVY
import groovy.transform.CompileStatic

@CompileStatic
class Calc {
  int add(int a, int b) { a + b }
}

Under @CompileStatic the compiler resolves calls at compile time like Java, and metaclass changes are ignored for that code. @TypeChecked keeps dynamic dispatch but verifies types at compile time. Use dynamic Groovy for scripts, builders and tests, and static Groovy for hot paths and libraries.

Try it: a dispatch table in Java (stand-in)

This Java program models a metaclass: a registry from a class to named methods, looked up at call time, with a walk up the superclass chain as Groovy does. The "Groovy" side of the story is in the fences above; this just shows the mechanism.

Java Stand-in: a runtime method registry

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: multiple dispatch by runtime type (stand-in)

Java overloads bind to the declared type. To get Groovy's behavior you inspect the runtime type yourself:

Java Stand-in: static versus runtime overload choice

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. When does Groovy normally decide which method a call runs?

    Groovy dispatches dynamically on each call through the metaclass, unless the code is compiled with @CompileStatic.
  2. 2. Given Object x = "hi" and overloads f(Object) and f(String), which does Groovy call for f(x)?

    Groovy uses multiple dispatch based on the runtime type of the argument, so the String overload is chosen.
  3. 3. What does respondsTo(obj, "name") return when nothing matches?

    It returns a list of matching meta methods. An empty list is falsy in a Groovy condition.
  4. 4. What happens to metaclass changes inside @CompileStatic code?

    Statically compiled calls are bound at compile time, so runtime metaclass additions are not seen.

Summary

  • Groovy resolves method calls at runtime through each object's MetaClass.
  • Overloads are chosen by the runtime types of the arguments (multiple dispatch).
  • respondsTo and hasProperty support safe duck typing.
  • Class.metaClass.name = { ... } adds methods; metaClass.static adds static ones. Changes on a class are global.
  • @CompileStatic turns dynamic dispatch off for speed and compile-time checks.

Next: Expando and ExpandoMetaClass