Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Dynamic Features and Metaprogramming

Categories and Runtime Mixins in Groovy

Add methods to classes only inside a scope with Groovy categories and use(), build reusable extension modules, and compose behavior with traits and runtime mixins.

Changing a class through metaClass is global and permanent. A category is the polite alternative: it adds methods to a class only for the duration of a block, in the current thread, and then everything goes back to normal. It is perfect for small unit-conversion or formatting helpers where you want 5.minutes to work in one place without polluting the whole program.

Groovy cannot run on this site, so the Groovy code is read-only. The Java stand-ins use a scoped (thread-local) table of extra methods to show the mechanism.

Writing a category

A category is a class with static methods whose first parameter is the type being extended. Inside a use block, those methods can be called as if they belonged to that type.

GROOVY
class DurationCategory {
  static Integer getMinutes(Integer self) { self * 60 }
  static Integer getHours(Integer self)   { self * 3600 }
  static String shout(String self)        { self.toUpperCase() + "!" }
}

use(DurationCategory) {
  println 5.minutes        // 300
  println 2.hours          // 7200
  println "hey".shout()    // HEY!
}

// outside the block the methods are gone
// 5.minutes   -> MissingPropertyException

Details worth remembering:

  • A static getXxx(Type self) becomes a property xxx. That is why 5.minutes has no parentheses.
  • A static xxx(Type self, args...) becomes a method.
  • The effect is limited to the current thread and the block, including methods called from inside it.
  • You can pass several categories: use(CatA, CatB) { ... }.

Categories with the @Category annotation

Writing self everywhere is a little noisy. The @Category transformation lets you write instance-style code:

GROOVY
@Category(Integer)
class Time {
  int getMinutes() { this * 60 }
  int getHours()   { this * 3600 }
}

use(Time) {
  println 3.hours   // 10800
}

Inside the class, this refers to the extended object. Under the hood the compiler converts these methods to the static form above.

Why not just use metaClass?

metaClass use(Category)
Scope Whole JVM, until reset One block, one thread
Cleanup Manual Automatic
Test isolation Can leak between tests Safe
Speed Normal after setup Slower inside the block

If your goal is a project-wide nicety, there is a third and often best option, the extension module.

Extension modules

An extension module is a normal class with static methods (like a category) plus a descriptor file, META-INF/groovy/org.codehaus.groovy.runtime.ExtensionModule, listing it:

TEXT
moduleName=my-extensions
moduleVersion=1.0
extensionClasses=com.example.StringExtensions
GROOVY
package com.example

class StringExtensions {
  static String slugify(String self) {
    self.toLowerCase().replaceAll(/[^a-z0-9]+/, "-").replaceAll(/^-|-$/, "")
  }
}

With that jar on the classpath, "Hello, Big World!".slugify() works everywhere and is understood by @CompileStatic and IDEs, because it is discovered at compile time. This is exactly how Groovy's own GDK methods such as List.collect or String.reverse() are shipped.

Mixing in behavior

Older Groovy offered @Mixin and Class.mixin(Other) to copy methods from one class into another at runtime. @Mixin is deprecated and removed in recent versions. The modern replacement is traits, which compose at compile time with proper types (see Traits). You can still add a trait to a single object at runtime with as:

GROOVY
trait Flyer {
  String fly() { "${name} flies" }
}

class Bird { String name }

def b = new Bird(name: "Tweety")
def flyingBird = b.withTraits(Flyer)
println flyingBird.fly()        // Tweety flies
println(flyingBird instanceof Flyer)   // true

withTraits returns a proxy that also implements the trait, so one object can gain abilities without a new class in the hierarchy.

Choosing a technique

flowchart TD
  A["Need extra methods on a class"] --> B{"Do you own the class?"}
  B -- yes --> C["Normal method or a trait"]
  B -- no --> D{"Everywhere or one place?"}
  D -- everywhere --> E["Extension module"]
  D -- "one block" --> F["Category with use"]
  D -- "one object" --> G["withTraits or per-instance metaClass"]

Rule of thumb: the narrower the scope, the safer the change.

Try it: a scoped extension in Java (stand-in)

The program keeps a thread-local table of extra "methods". use installs them, runs a block, and always removes them, like a category block.

Java Stand-in: category-style scoped methods

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: adding abilities to one object (stand-in)

Java's Proxy can give a single object an extra interface, like withTraits.

Java Stand-in: withTraits via a proxy

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 is the shape of a category method that extends Integer?

    Category methods are static, and the first parameter is the receiver that the call is made on.
  2. 2. How long do category methods stay active?

    use(Category) { } scopes the extra methods to the block and to the calling thread.
  3. 3. What does a static method named getMinutes(Integer self) allow?

    Groovy treats getXxx as a property getter, so 5.minutes works inside use.
  4. 4. What replaces the deprecated @Mixin in modern Groovy?

    Traits compose behavior with type safety at compile time, and withTraits applies them to a single object at runtime.

Summary

  • A category is a class of static methods whose first parameter is the extended type, activated by use(Category) { }.
  • Effects are scoped to the block and thread, so they are safe for tests.
  • @Category(Type) lets you write the methods with this.
  • Extension modules publish extensions project-wide and work with static compilation.
  • Traits (and withTraits) replace the old @Mixin.

Next: AST Transformations