Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Dynamic Features and Metaprogramming

methodMissing and propertyMissing in Groovy

Intercept calls to methods and properties that do not exist: methodMissing, propertyMissing, invokeMethod, caching generated methods, and dynamic finders.

What should happen when code calls repo.findByName("Ada") and no such method was ever written? In Java, a compile error. In Groovy, the call is delivered to a hook you control. That hook is how dynamic finders, proxies, fluent builders and many DSLs are made: the object interprets the name of the call instead of looking it up.

Groovy is not available on this site, so the Groovy fences are read-only. The Java programs are labelled stand-ins that route unknown names through a handler, the same idea.

methodMissing

If Groovy cannot find a method, it calls methodMissing(String name, Object args) on the receiver, when that method exists:

GROOVY
class Greeter {
  def methodMissing(String name, Object args) {
    if (name.startsWith("sayHelloTo")) {
      return "Hello, ${name - 'sayHelloTo'}!"
    }
    throw new MissingMethodException(name, Greeter, args)
  }
}

def g = new Greeter()
println g.sayHelloToAda()     // Hello, Ada!
println g.sayHelloToLinus()   // Hello, Linus!
g.explode()                   // MissingMethodException

Always finish with a throw new MissingMethodException(...) for names you do not handle. Swallowing every call hides typos.

args is an array of the actual arguments, so g.sum(1, 2, 3) gives args == [1, 2, 3].

propertyMissing

The same idea for properties. Groovy calls propertyMissing(String name) for reads and propertyMissing(String name, value) for writes:

GROOVY
class Settings {
  private Map data = [:]

  def propertyMissing(String name)            { data[name] }
  def propertyMissing(String name, def value) { data[name] = value }
}

def s = new Settings()
s.theme = "dark"
s.fontSize = 14
println s.theme       // dark
println s.fontSize    // 14
println s.unknown     // null

This gives you object syntax over a map, with the chance to validate or convert values in one place.

Caching the generated method

If methodMissing is expensive, register a real method the first time and let later calls skip the hook entirely. That is the traditional "intercept, cache, invoke" pattern:

GROOVY
class Repo {
  List rows = [[name: "Ada", city: "London"], [name: "Linus", city: "Helsinki"]]

  def methodMissing(String name, Object args) {
    def m = name =~ /^findBy(\w+)$/
    if (!m) throw new MissingMethodException(name, Repo, args)

    String field = m[0][1].toLowerCase()
    // register a real method on the metaclass for next time
    Repo.metaClass."$name" = { Object value -> rows.findAll { it[field] == value } }
    return rows.findAll { it[field] == args[0] }
  }
}

def r = new Repo()
println r.findByCity("London")   // [[name:Ada, city:London]]
println r.findByName("Linus")    // [[name:Linus, city:Helsinki]]

Repo.metaClass."$name" = ... uses a GString as the property name, which is how you define a method whose name is computed.

invokeMethod and getProperty

methodMissing runs only for missing methods. Two older hooks intercept more:

  • invokeMethod(String name, Object args): if a class implements GroovyInterceptable, every method call on it goes through invokeMethod, existing or not.
  • getProperty(String name) / setProperty(String name, Object value): override these to catch every property read or write.
GROOVY
class Tracer implements GroovyInterceptable {
  List log = []

  def invokeMethod(String name, Object args) {
    log << name
    // call the real method through the metaclass
    metaClass.getMetaMethod(name, args)?.invoke(this, args)
  }

  def hello() { "hi" }
}

def t = new Tracer()
t.hello()
t.hello()
println t.log   // [hello, hello]

Note that accessing log inside invokeMethod reads a property and does not trigger the hook. Calling another method on this would, so be careful about infinite recursion.

Intercepting every call slows the object down and makes stack traces harder to read. Prefer methodMissing and propertyMissing, which cost nothing for calls that resolve normally.

When is this the right tool?

Goal Use
Dynamic finders, "any name starting with..." methodMissing with a regex
Object syntax over maps/config propertyMissing
Logging/timing/security of every call GroovyInterceptable or a proxy
Extra methods on a class you do not own metaClass or a category

Compare with Java's java.lang.reflect.Proxy: it needs an interface and gives you invoke(Object proxy, Method m, Object[] args). In Groovy no interface is required.

Try it: dynamic finders through a handler (stand-in)

The Java version receives a method name as a string and parses it, exactly what methodMissing does.

Java Stand-in: findByXxx dispatcher

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 call-logging proxy (stand-in)

Java's own Proxy plays the part of GroovyInterceptable, recording every call before forwarding it.

Java Stand-in: intercepting every call

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 is methodMissing called?

    methodMissing is a fallback. Calls that resolve normally never reach it.
  2. 2. What should a methodMissing implementation do with names it does not handle?

    Throwing MissingMethodException keeps typos visible instead of silently ignoring them.
  3. 3. Which interface makes every method call pass through invokeMethod?

    GroovyInterceptable marks a class whose invokeMethod intercepts all calls, existing methods included.
  4. 4. Why register a real method on the metaClass inside methodMissing?

    After registration the metaclass finds the method directly, so the pattern matching is done once per name.

Summary

  • methodMissing(name, args) and propertyMissing(name) run only when lookup fails.
  • Always throw MissingMethodException for names you do not support.
  • Cache by adding a real method to the metaclass after the first call.
  • GroovyInterceptable with invokeMethod intercepts everything, at a cost.
  • These hooks power dynamic finders, config objects and builders.

Next: Categories and Runtime Mixins